5. if and for Statements
Printing out Multiples of a Number
We have mischievously decided to leave out a complete description of for
loops in this chapter as well. However, it will be provided later. For the time being, ignore the unexplained details and concentrate on the intended purpose of for
loops: repeating (i.e. iterating). Iteration is what for
loops do best.
If you happen to be SO impatient, you can take a quick glance here.
Another example of utilizing for
loops
is presented here: a program that prints out the first five multiples of the number 3:
#include <iostream> using namespace std; int main() { for(double i=1; i<=5; i++) cout << i*3 << endl; }
Please type in and execute this program. Upon execution, the following numbers will appear on your screen:
3 6 9 12 15
In the given for loop, the variable i
gets
assigned the values 1, 2, 3, 4, 5 in this exact order. However, in the cout
statement the value of variable i
gets multiplied by number 3, and
that ultimately results in the desired list of the first five multiples of the number
3.
The variable counting the iterations of a for
loop
(in this example: i
) is called the loop variable. There
is no mandate requiring that it should be named 'i
'. You can
use any other valid name. However, it is a common practice to name loop
variables with the letters i
, j
, k
.
In the following example we have renamed i
into num
, and also
slightly redesigned the printout:
#include <iostream> using namespace std; int main() { for(double num=1; num<=5; num++) cout << num << "*3=" << num*3 << endl; }
By executing this program, you should get the following printout:
1*3=3 2*3=6 3*3=9 4*3=12 5*3=15
The real change in this program is in the statement:
cout << num << "*3=" << num*3 << endl;
The best way to understand the behavior of
this program is to imagine that the execution of the for
loop is
suspended in time, for example at the fourth iteration when the loop variable num
assumes
the value 4. To execute the highlighted statement, first we print out the value
of the variable num
, that is the number 4; then we print out the string "*3="
and finally, the value of the expression num*3
,
which is the number 12. Altogether, the fourth iteration outputs the following
on standard output:
4*3=12