Sams Teach Yourself C++ in 21 Days

(singke) #1

Advanced forLoops ......................................................................................


forstatements are powerful and flexible. The three independent statements (initial-
ization,test, and action) lend themselves to a number of variations.

Multiple Initialization and Increments
It is not uncommon to initialize more than one variable, to test a compound logical
expression, and to execute more than one statement. The initialization and the action can
be replaced by multiple C++ statements, each separated by a comma. Listing 7.10
demonstrates the initialization and increment of two variables.

LISTING7.10 Demonstrating Multiple Statements in forLoops
1: //Listing 7.10
2: // Demonstrates multiple statements in
3: // for loops
4: #include <iostream>
5:
6: int main()
7: {
8:
9: for (int i=0, j=0; i<3; i++, j++)
10: std::cout << “i: “ << i << “ j: “ << j << std::endl;
11: return 0;
12: }

i: 0 j: 0
i: 1 j: 1
i: 2 j: 2
On line 9, two variables,iand j, are each initialized with the value 0. A comma
is used to separate the two separate expressions. You can also see that these ini-
tializations are separated from the test condition by the expected semicolon.
When this program executes, the test (i<3) is evaluated, and because it is true, the body
of the forstatement is executed, where the values are printed. Finally, the third clause in
the forstatement is executed. As you can see, two expressions are here as well. In this
case, both iand jare incremented.
After line 10 completes, the condition is evaluated again, and if it remains true, the
actions are repeated (iand jare again incremented), and the body of the loop is exe-
cuted again. This continues until the test fails, in which case the action statement is not
executed, and control falls out of the loop.

OUTPUT


190 Day 7


ANALYSIS
Free download pdf