Exercise: Addition Calculator

Exercise 1 Very easy

Prerequisites for the exercise

  1. PHP Basics

Objective

Create a program that asks the user to input two integers and then outputs their sum.

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:

x: <input>

Here, <input> denotes the input of the user.

Similarly, the second input should be of the form:

y: <input>

The output should be:

The sum is: <sum>

where <sum> is the sum of the input integers.

Shown below is an example:

x: 10 y: 20 The sum is: 30
View Solution

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);
We could use other variable names as well for the input numbers such as $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:

x: 100 y: -20 The sum is: 80

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.