Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 193

7


LISTING7.13 Illustrates the Null Statement in a forLoop


1: //Listing 7.13
2: //Demonstrates null statement
3: // as body of for loop
4:
5: #include <iostream>
6: int main()
7: {
8: for (int i = 0; i<5; std::cout << “i: “ << i++ << std::endl)
9: ;
10: return 0;
11: }

i: 0
i: 1
i: 2
i: 3
i: 4
The forloop on line 8 includes three statements: The initializationstatement
establishes the counter iand initializes it to 0. The conditionstatement tests for
i<5, and the actionstatement prints the value in iand increments it.
Nothing is left to do in the body of the forloop, so the null statement (;) is used. Note
that this is not a well-designed forloop: The action statement is doing far too much.
This would be better rewritten as
8: for (int i = 0; i<5; i++)
9: cout << “i: “ << i << endl;
Although both do the same thing, this example is easier to understand.

Nesting Loops ................................................................................................


Any of the loop can be nested within the body of another. The inner loop will be exe-
cuted in full for every execution of the outer loop. Listing 7.14 illustrates writing marks
into a matrix using nested forloops.

LISTING7.14 Illustrates Nested forLoops


1: //Listing 7.14
2: //Illustrates nested for loops
3: #include <iostream>
4:
5: int main()
6: {
7: using namespace std;

OUTPUT


ANALYSIS
Free download pdf