Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 189

7


LISTING7.9 Demonstrating the forLoop


1: // Listing 7.9
2: // Looping with for
3:
4: #include <iostream>
5:
6: int main()
7: {
8: int counter;
9: for (counter = 0; counter < 5; counter++)
10: std::cout << “Looping! “;
11:
12: std::cout << “\nCounter: “ << counter << std::endl;
13: return 0;
14: }

Looping! Looping! Looping! Looping! Looping!
Counter: 5.
The forstatement on line 9 combines the initialization of counter, the test that
counteris less than 5 , and the increment of counterall into one line. The body
of the forstatement is on line 10. Of course, a block could be used here as well.

OUTPUT


ANALYSIS

The forStatement
The syntax for the forstatement is as follows:
for (initialization; test; action)
statement;
The initializationstatement is used to initialize the state of a counter, or to otherwise
prepare for the loop. testis any C++ expression and is evaluated each time through the
loop. If testis true, the body of the forloop is executed and then the action in the
header is executed (typically the counter is incremented).
Example 1
// print Hello ten times
for (int i = 0; i<10; i++)
cout << “Hello! “;
Example 2
for (int i = 0; i < 10; i++)
{
cout << “Hello!” << endl;
cout << “the value of i is: “ << i << endl;
}
Free download pdf