Objective
Create a program that asks the user to input two integers and then outputs their sum.
Difficulty
Description
In this exercise, you have to create a program that asks the user to input two integers, one-by-one, and then outputs their sum.
The first input prompt of the program should be of the form shown below:
Here, <input>
denotes the input of the user.
Similarly, the second input should be of the form:
The output should be:
where <sum>
is the sum of the input integers.
Shown below is an example:
New file
Inside the directory you created for this course on PHP, create a new folder called Exercise-1-Addition-Calculator and put the .php solution files for this exercise within it.
Solution
As instructed in the question, first we need to ask the user to input a value for x
and then a value for y
, with the prompts 'x: '
and 'y: '
, respectively.
<?php
echo 'x: ';
$y = fgets(STDIN);
echo 'y: ';
$x = fgets(STDIN);
$a
and $b
, but since the prompt messages specifically use the names 'x'
and 'y'
, it would be straightforward to go with these names for the variables as well.Next, up we need to convert both $x
and $y
to integers using the (int)
typecast:
<?php
echo 'x: ';
$y = fgets(STDIN);
echo 'y: ';
$x = fgets(STDIN);
// Convert to int.
$x = (int) $x;
$y = (int) $y;
Finally, we just ought to add x
and y
together and print out the result, as desired in the exercise.
<?php
echo 'x: ';
$x = fgets(STDIN);
echo 'y: ';
$y = fgets(STDIN);
// Convert to int.
$x = (int) $x;
$y = (int) $y;
echo 'The sum is: ', $x + $y;
Below, we use this program to add two numbers:
Slight improvement
Note that instead of converting the variables separately in lines 10 - 11 above, we could have used the (int)
typecast directly before the fgets()
call (in lines 4 and 7). This is definitely much more compact than the code above.
<?php
echo 'x: ';
$x = (int) fgets(STDIN);
echo 'y: ';
$y = (int) fgets(STDIN);
echo 'The sum is: ', $x + $y;
Semantically, this code snippet is exactly similar to the last one i.e. both the code snippets do exactly the same thing.