Chapter 3
Chapter 3
In the previous chapter, we looked at declaring variables, assigning values to them, and displaying them
on the monitor. In this chapter, we will show how to combine variables into arithmetic expressions using
arithmetic operators such as addition, subtraction, and multiplication. We will also describe how to input
values into integer, floating-point, and string variables using the keyboard. By accepting data from input
devices, a program can be written to produce output based on the input received. This gives the program
the ability to handle a wide range of input values typically encountered in the real world. Finally, we will
explain how to use some built-in functions in C++ such as ceil and floor.
In the previous chapter, we discussed the problem of finding the amount of carpet required to cover a
rectangular room of width 10 metres and length 15 metres. We explained how the integer variables, width
and length, could be used to store the width and length of the room, respectively. We also declared an
integer variable, area, to store the amount of carpet required to cover the room. We will now show how
to calculate the value of area.
The value of the area variable can be calculated by multiplying the value of the width variable by the value
of the length variable. This can be done as follows:
The equal sign indicates that this is an assignment statement. The calculation on the right-hand side is
called an arithmetic expression. After the arithmetic expression is evaluated, the result is stored in the
variable on the left-hand side of the assignment statement.
Once the value of (width * length) is calculated and stored in the area variable, the value of area can
be displayed on the monitor using a cout statement as follows:
1
The complete program to determine the amount of carpet required to cover the room is given below:
#include <iostream>
using namespace std;
int main () {
int width;
int length;
int area;
width = 10;
length = 15;
return 0;
}
An arithmetic expression is formed by combining variables and numbers (i.e., operands) in different ways
using arithmetic operators such as addition, subtraction, and multiplication. An arithmetic operator takes
two numbers as operands and returns a single numerical value. In the carpet program, the multiplication
operator takes the value of the width variable and the value of the length variable as operands and returns
the product of the operands. Table 3.1 gives a list of some arithmetic operators which can be used to
formulate an arithmetic expression:
2
The right-hand side of each of the following assignment statements is an example of an arithmetic
expression:
An arithmetic expression is evaluated by moving from left to right. The ordinary rules of precedence of
arithmetic operators apply—multiplication and division will be done before addition and subtraction. To
override these rules, parentheses can be used, as shown in the third example above. Parentheses can also
be used if you are in doubt about the order of evaluation of an expression. For example, suppose we have
the following expression:
x – y * 10
Do we subtract y from x and then multiply the result by 10 or do we multiply y by 10 and then subtract
the result from x? The program will do the latter. If we wanted to ensure that the former is done, the
expression can be written using parentheses as follows:
(x – y) * 10
Before concluding this section on arithmetic expressions, it is interesting to note what is achieved by the
assignment statement,
count = count + 1;
Suppose count currently has the value 10. The expression on the right-hand side is evaluated. This adds 1
to the value currently stored in the count variable (i.e., 10). The result is 11 and 11 is then put into the
memory location on the left-hand side of the assignment statement. Incidentally, this memory location is
count. So, the count variable will now have the value 11. Effectively, the statement adds one to the value
currently stored in the count variable. Similarly, the following statement subtracts one from the value
currently stored in the count variable.
count = count - 1;
3
3.3 The Modulus Operator (%)
The modulus operator can be used to find the remainder when its first integer operand is divided by its
second integer operand. For example, 10 % 4 returns 2, since the remainder when 10 is divided by 4 is 2.
Consider also the expressions 10 % 5 and 12 % 3. The value of 10 % 5 is zero and the value of 12 % 3 is
also zero. In the first case, 5 is a factor of 10 and in the second case, 3 is a factor of 12. In both cases, the
remainder is zero.
In general, if x % y is equal to zero, it implies that y is a factor of x. In a subsequent chapter, we will show
how the modulus operator can be used to find all the factors of a certain integer. Also, if an integer has
no factors, the integer is a prime number. It follows that the modulus operator can be used to determine
if a given number is a prime number. We will also look at this in a later chapter.
int numerator;
int denominator;
int x;
Suppose numerator has the value 3 and denominator has the value 10, what is the value of x after the
following assignment statement is executed?
x = numerator / denominator;
The value of 3/10 works out to 0.3. However, since the operands of 3/10 are both integer quantities, the
computer truncates the fractional part and the expression returns zero, which is assigned to x. So, the
value of x is zero.
Suppose now that numerator has the value 9 and denominator has the value 10. What is the value of x
after the same assignment statement is executed?
A reasonable answer is that x will have the value 1, since 9/10 works out to 0.9, which, when rounded up
to the nearest integer, results in 1. However, the answer is still zero. Again, since integer division takes
place, the fractional part is simply truncated, resulting in zero being stored in x.
4
Let’s declare x as a floating-point variable so that it can hold a fractional quantity:
float x;
Suppose that numerator has the value 9 and that denominator has the value 10. What is the value of x
after the same assignment statement is executed?
x = numerator / denominator;
A reasonable answer is that x will have the value 0.9 since it is a floating-point variable which can store a
fractional part. But, yet again, x has the value 0.0 after the statement is executed. This happens because
the expression (numerator / denominator) still performs integer division since both numerator and
denominator are integer quantities.
A simple way to get around this problem is to multiply either numerator or denominator by 1.0 which
forces the division to be floating-point division since at least one of the values involved is now a floating-
point value:
By doing this, x will have the value 0.9. This example illustrates that you need to be very careful when
writing expressions in a program that involve division, where the operands are integers.
The program to calculate the amount of carpet required to cover a rectangular room executes successfully
but produces the same output every time it is executed. To find the amount of carpet required for a room
with different dimensions, modifications must be made to the source code of the program and the
program must be re-compiled and executed. This is not very practical.
An alternative is to let the user specify the dimensions of the room using an input device. In other words,
the program should allow the user to specify the value for the width variable as well as the value for the
length variable. This can be done using the keyboard. Accepting a value from the keyboard (typed by the
user) and storing it in a variable is known as inputting a value. The cin statement is used to input a value
from the keyboard to a named memory location. For example,
5
cin >> width;
This statement causes the program to wait for the user to type an integer value at the keyboard. When
the user presses the Enter key, the value will be stored in the width variable. The program will not
proceed until the user types an integer value and presses Enter.
It should be observed that the double arrows in a cin statement point in the opposite direction to the
ones used in a cout statement.
It is helpful to inform the user what value must be typed at the keyboard before the cin statement is
written. This can be done by using a cout statement before the cin statement. For example,
The process of inputting values from the user and storing the values in their corresponding memory
locations is depicted in Figure 3.1.
10 15
width length
User types values
for width and
length at keyboard area
memory
user
6
After the values for width and length have been entered by the user at the keyboard, the value for area
is calculated in the usual manner:
The complete program to determine the amount of carpet required, where the dimension of the room is
specified by the user at the keyboard, is given below.
#include <iostream>
using namespace std;
int main () {
int width;
int length;
int area;
return 0;
}
Each time the program is executed, the user can specify different values for the width and length of the
room and the program will calculate and display the area correctly based on these values. For example,
suppose the values 12 and 14 are entered when the program requests the width and length of the room:
The program calculates and displays the amount of carpet required for the room with the given
dimension:
7
Width of the room: 12
Length of the room: 14
Amount of carpet required: 168
If the values entered for the width and length of the room were 15 and 20, respectively, the program will
output that the amount of carpet required is 300. Thus, the program correctly calculates the amount of
carpet required for a rectangular room of any dimension.
Although the carpet program is quite simple, it demonstrates three important features of most programs:
1. It accepts input from the user via an input device (in this case, the keyboard).
2. It processes the input data in some way (in particular, it uses the ALU to perform the calculation
to find the amount of carpet required).
3. It produces output for the user using an output device (in this case, the monitor) which solves the
given problem.
A floating-point value can also be input into a program using a cin statement with a floating-point
variable. Similarly, a string value can be input into a program using a cin statement with a string variable.
For example,
float interestRate;
string firstName, lastName;
cout << "Please enter the first name of the customer: ";
cin >> firstName;
cout << "Please enter the last name of the customer: ";
cin >> lastName;
A typical computer program makes use of building blocks known as functions. Some of the functions that
a program will need have already been written and are included in the C++ programming language. Other
functions need to be written from scratch. In a later chapter, we will explain how to write functions. In
8
this chapter, we will show how to use functions that are already included in the C++ programming
language.
Consider once again the program to carpet a room where the width and the length are floating point
quantities. The area is calculated in the usual manner:
Suppose width has the value 15.5 and length has the value 20.2. Then, the value of area will be 313.1.
Now, suppose carpet is sold in whole number quantities. We will therefore need to buy 314 square metres
of carpet. The number 314 is the smallest integer greater than or equal to 313.1. Mathematically, it is
referred to as the ceiling of 313.1. But, how do we find the ceiling of any number? We can use the built-
in function, ceil, which finds the ceiling of a number. This function can be used as follows:
float amount;
When the cout statement executes, the value 314 is displayed on the monitor. Table 3.2 gives some more
examples of using the ceil function.
Example Description
float amount; amount has the value 314.
amount = ceil (313.6);
float amount; amount has the value 313.
amount = ceil (313.0);
float amount; amount has the value 221. Note that the ceil
float area;
area = 220.5;
function can work with a floating-point value as well
amount = ceil (area); as with a floating-point variable.
Though one might expect the ceil function to return an integer quantity, it actually returns a floating-point
value with zero as the fractional part. Thus, the variable to the left of the equal sign in the assignment
statement can also be a variable of type float or double.
9
A related built-in function is the floor function. The floor of a number is the greatest integer that is less
than or equal to the number. For example, the floor of 10.8 is 10. Some more examples of the floor
function are given in Table 3.3.
Example Description
float amount; amount has the value 313.
amount = floor (313.6);
float amount; amount has the value 313.
amount = floor (313.0);
float amount; amount has the value 220. Note that the floor
float area;
area = 220.5;
function can work with a floating-point value as well
amount = floor (area); as with a floating-point variable.
In order to use the ceil and floor functions, the following line must be placed at the top of your program:
#include <cmath>
So, the first few lines of your program will now become:
#include <iostream>
#include <cmath>
using namespace std;
It should be noted that you do not need the line, #include <cmath>, if you will not be using the ceil or
floor functions in your program.
The importance of writing source code in a readable manner was emphasized in the previous chapters.
Another way to improve the readability of source code is to use comments. Comments are used to
describe the different pieces of code in a program. They are also used to document programming steps
which may be hard to understand.
Comments in the source code are ignored by the compiler. So, like white space, they do not affect the
object code in any way. Two types of comments that are typically used in a program are multi-line
comments and single-line comments.
10
A multi-line comment spans one or more lines. It begins with “/*” and ends with “*/”. For example,
/*
Program name: Carpet.cpp
Written by: John Doe
Date: September 13, 2021
*/
A single-line comment is usually written in the same line containing a programming statement. It is
specified using “//” before the start of the comment. For example,
When the “//” is encountered, all the remaining characters in the line are ignored by the compiler. This
type of comment can also be used to disable a statement without deleting it from a program. To do so,
put “//” in front of the statement, e.g.,
3.8 Exercises
1. Suppose that the values of the integer variables x, y, and z are 25, 23, and 30, respectively. What are
the values of x, y, and z after the execution of each of the following statements?
(a) x = y + z;
(b) y = y / 2;
(c) z = z % 4;
2. Suppose that x is a floating-point variable, and y and z are integer variables with values 8 and 5,
respectively. What is the value of x after the execution of each of the following statements?
(a) x = y / z; (b) x = (y / z) + 1.0; (c) x = (y * 1.0) / z;
11
3. Suppose that the values of the integer variables x and y are 3 and 5, respectively. What is the value
of the integer variable z after the execution of each of the following statements?
(a) z = (x / y) * (y / x);
(b) z = x % y;
(c) z = y % z;
4. Without using a C++ compiler, determine what output is produced by the following statements:
int a, b, c;
a = 13;
b = a + 12;
c = a + b;
a = a + 11;
5. Write a program that calculates and displays the area and perimeter of a rectangle. Your program
should allow the user to enter the width and length of the rectangle at the keyboard.
6. Write a program which, when executed, will produce the following output. Note that the data after
the question mark (shown in bold) must be input by the user at the keyboard.
12