Exercise: Sorted Numbers

Exercise 3 Very easy

Prerequisites for the exercise

  1. Python Data Types
  2. All previous chapters

Objective

Output three input numbers in ascending order.

Description

Ask the user to input three different integers by means of three different input prompts.

The general form of all the three input prompts together is shown as follows:

x: <input>
y: <input>
z: <input>

Once this is done, finally output these numbers in ascending order (i.e. smallest number first, largest number last) in the following format .

Sorted numbers: <int1> <int2> <int3>

Where <int1>, <int2>, and <int3>, are the input numbers.

Below shown is an example:

x: 150
y: 32
z: 50
Sorted numbers: 32 50 150
View Solution

New file

Inside the directory you created for this course on PHP, create a new folder called Exercise-3-Sorted-Numbers and put the .php solution files for this exercise within it.

Solution

We need to get three inputs from the user, hence we start by laying out three different fgets() calls preceded by the respective prompt messages:

<?php

$nums = [];

echo 'x: ';
array_push($nums, (int) fgets(STDIN));

echo 'y: ';
array_push($nums, (int) fgets(STDIN));

echo 'z: ';
array_push($nums, (int) fgets(STDIN));

Take note of the (int) typecast before each fgets() call — this is done to make it apparent programmatically and visibly that we want to add the input number to the array $nums in the form of an integer.

By nature, fgets() always returns a string.

After obtaining the inputs, the next step is to sort the $nums array. This is done below:

<?php

$nums = [];

echo 'x: ';
array_push($nums, (int) fgets(STDIN));

echo 'y: ';
array_push($nums, (int) fgets(STDIN));

echo 'z: ';
array_push($nums, (int) fgets(STDIN));

// Sort the numbers.
sort($nums); echo 'Sorted numbers: ', $nums[0], ' ', $nums[1], ' ', $nums[2];
Sorting numbers in PHP without having a list can be an extremely challenging task!

To end with, we print all the three elements of the array (which is now in sorted order), one after another making sure that the desirable format of the output as indicated in the exercise's question is followed:

<?php

$nums = [];

echo 'x: ';
array_push($nums, (int) fgets(STDIN));

echo 'y: ';
array_push($nums, (int) fgets(STDIN));

echo 'z: ';
array_push($nums, (int) fgets(STDIN));

// Sort the numbers.
sort($nums);

echo 'Sorted numbers: ', $nums[0], ' ', $nums[1], ' ', $nums[2];

This completes our exercise!

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage