Next: Example Program: Student Mark
Up: The for statement
Previous: Example for statement: Print
The following loop tabulates the sin function from x = 0.0
to x = 1.6
in steps of 0.1
.
int i; float x; for (i = 0; i <= 16; i++) { x = 0.1 * i; cout << x << " " << sin(x) << endl; }
Download program.Note how an integer variable
i
is used to control the loop
while inside the loop the corresponding value of x
is calculated
as a function of i
. This is preferable to the following:float x; for (x = 0.0; x <= 1.6; x += 0.1) cout << x << " " << sin(x) << endl;The problem with the above is that floating point variables are not held exactly, thus 0.1 might be represented by something slightly larger than 0.1. Then after continually adding 0.1 to
x
the
final value that should be 1.6 may actually be something like 1.60001.
Thus the test x <= 1.6
would fail prematurely and the last line
of the table would not be printed. This could be corrected by making
the test x <= 1.605
say.
In general it is probably best to use integer variables as control variables in for loops.