for Loops

When programming while loops, you'll often find yourself setting up a starting condition, testing to see if the condition is true, and incrementing or otherwise changing a variable each time through the loop. Listing 6.7 demonstrates this.

Listing 6.7. while Loop Reexamined
 0:  // Listing 6.7
 1:  // Looping with while
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int counter = 0;
 7:
 8:      while(counter < 5)
 9:      {
10:          counter++;
11:          std::cout << "Looping!  ";
12:      }
13:
14:      std::cout << "
Counter: " << counter << ".
";
15:      return 0;
16:  }


Looping!  Looping!  Looping!  Looping!  Looping!
counter: 5.
					

The condition is set on line 6: counter is initialized to 0. On line 8 counter is tested to see if it is less than 5. counter is incremented on line 10. On line 11, a simple message is printed, but you can imagine that more important work could be done for each increment of the counter.


Initialization, Test, and Increment

A for loop combines the three steps of initialization, test, and increment into one statement. A for statement consists of the keyword for followed by a pair of parentheses. Within the parentheses are three statements separated by semicolons.

The first statement is the initialization. Any legal C++ statement can be put here, but typically this is used to create and initialize a counting variable. Statement two is the test, and any legal C++ expression can be used there. This serves the same role as the condition in the while loop. Statement three is the action. Typically a value is incremented or decremented, although any legal C++ statement can be put there. Note that statements one and three can be any legal C++ statement, but statement two must be an expression—a C++ statement that returns a value. Listing 6.8 demonstrates the for loop.

Listing 6.8. Demonstrating the for Loop
 0:  // Listing 6.8
 1:  // Looping with for
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int counter;
 7:      for (counter = 0; counter < 5; counter++)
 8:          std::cout << "Looping! ";
 9:
10:      std::cout << "
Counter: " << counter << ".
";
11:      return 0;
12:  }


Looping!  Looping!  Looping!  Looping!  Looping!
counter: 5.

The for statement on line 7 combines the initialization of counter, the test that counter is less than 5, and the action to increment to counter all into one line. The body of the for statement is on line 8. Of course, a block could be used here as well.


Advanced for Loops

for statements are powerful and flexible. The three independent statements (initialization, test, and action) lend themselves to a number of variations. A for loop works in the following sequence:

1.
Performs the operations in the initialization.

2.
Evaluates the condition.

3.
If the condition is true, executes the loop and then the action statement.

After each time through the loop, it repeats steps 2 and 3.

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 action statements can be replaced by multiple C++ statements, each separated by a comma. Listing 6.9 demonstrates the initialization and incrementing of two variables.

Listing 6.9. Demonstrating Multiple Statements in for Loops
 0:   //listing 6.9
 1:   // demonstrates multiple statements in
 2:   // for loops
 3:  #include <iostream>
 4:
 5:  int main()
 6:  {
 7:      for (int i=0, j=0; i<3; i++, j++)
 8:          std::cout << "i: " << i << " j: " << j << std::endl;
 9:      return 0;
10:  }


i: 0  j: 0
i: 1  j: 1
i: 2  j: 2

On line 7, two variables, i and j, are each initialized with the value 0. The test (i<3) is evaluated, and because it is true, the body of the for statement is executed and the values are printed. Finally, the third clause in the for statement is executed, and i and j are incremented.


After line 8 completes, the condition is evaluated again, and if it remains true the actions are repeated (i and j are again incremented), and the body of the loop is executed again. This continues until the test fails, in which case the action statement is not executed, and control falls out of the loop.

Null Statements in for Loops

Any or all of the statements in a for loop can be null. To accomplish this, use the semicolon to mark where the statement would have been. To create a for loop that acts exactly like a while loop, leave out the first and third statement. Listing 6.10 illustrates this idea.

Listing 6.10. Null Statements in for Loops
 0:  // Listing 6.10
 1:  // For loops with null statements
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int counter = 0;
 7:
 8:      for( ; counter < 5; )
 9:      {
10:          counter++;
11:          std::cout << "Looping!  ";
12:      }
13:
14:      std::cout << "
Counter: " << counter << ".
";
15:      return 0;
16:  }


Looping!  Looping!  Looping!  Looping!  Looping!
counter: 5.
							

You might recognize this as being exactly like the while loop illustrated previously. On line 6, the counter variable is initialized. The for statement on line 8 does not initialize any values, but it does include a test for counter < 5. There is no increment statement, so this loop behaves exactly as if it had been written like this:


while (counter < 5)

Once again, C++ gives you a number of ways to accomplish the same thing. No experienced C++ programmer would use a for loop in this way, but it does illustrate the flexibility of the for statement. In fact, it is possible, using break and continue, to create a for loop with none of the three statements. Listing 6.11 illustrates how.

Listing 6.11. Illustrating an Empty for Loop Statement
 0:  //Listing 6.11 illustrating
 1:  //empty for loop statement
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int counter=0;       // initialization
 7:      int max;
 8:      std::cout << "How many hellos?";
 9:      std::cin >> max;
10:      for (;;)          // a for loop that doesn't end
11:      {
12:          if (counter < max)       // test
13:          {
14:              std::cout << "Hello!
";
15:              counter++;          // increment
16:          }
17:          else
18:              break;
19:      }
20:      return 0;
21:  }


How many hellos?  3
Hello!
Hello!
Hello!
							

The for loop has now been pushed to its absolute limit. Initialization, test, and action have all been taken out of the for statement. The initialization is done on line 6, before the for loop begins. The test is done in a separate if statement on line 12, and if the test succeeds, the action—an increment to counter—is performed on line 15. If the test fails, breaking out of the loop occurs on line 18.


Although this particular program is somewhat absurd, there are times when a for(;;) loop or a while(1) loop is just what you'll want. You'll see an example of a more reasonable use of such loops when switch statements are discussed.

Empty for Loops

So much can be done in the header of a for statement that there are times you won't need the body to do anything at all. In that case, be sure to put a null statement (;) as the body of the loop. The semicolon can be on the same line as the header, but this is easy to overlook. Listing 6.12 illustrates how this is done.

Listing 6.12. Illustrating a null Statement in a for Loop
 0:  //Listing 6.12
 1:  //Demonstrates null statement
 2:  // as body of for loop
 3:  #include <iostream>
 4:
 5:  int main()
 6:  {
 7:      for (int i = 0; i<5; std::cout << "i: " << i++ << std::endl)
 8:          ;
 9:      return 0;
10:  }


i: 0
i: 1
i: 2
i: 3
i: 4
						

The for loop on line 7 includes three statements. The initialization statement establishes the counter i and initializes it to 0. The condition statement tests for i<5, and the action statement prints the value in i and increments it.


There is nothing left to do in the body of the for loop, so the null statement (;) is used. Note that this is not a well-designed for loop; the action statement is doing far too much. This would be better rewritten as

8:         for (int i = 0; i<5; i++)
9:              std::cout << "i: " << i << endl;

Although both do exactly the same thing, this example is easier to understand. Keep in mind that when you create a variable inside a for loop, it is local to that loop and only exists while the loop is executing.

Nested Loops

Loops can be nested, with one loop sitting in the body of another. The inner loop will be executed in full for every execution of the outer loop. Listing 6.13 illustrates writing marks into a matrix using nested for loops.

Listing 6.13. Nested for Loops
 0:  //Listing 6.13
 1:  //Illustrates nested for loops
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int rows, columns;
 7:      char theChar;
 8:      std::cout << "How many rows? ";
 9:      std::cin >> rows;
10:      std::cout << "How many columns? ";
11:      std::cin >> columns;
12:      std::cout << "What character? ";
13:      std::cin >> theChar;
14:      for (int i = 0; i<rows; i++)
15:      {
16:          for (int j = 0; j < columns; j++)
17:              std::cout << theChar;
18:          std::cout << "
";
19:      }
20:      return 0;
21:  }


How many rows? 4
How many columns?  12
What character?  x
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx

The user is prompted for the number of rows and columns and for a character to print. The first for loop, on line 14, initializes a counter (i) to 0, and then the body of the outer for loop is run.


On line 16, the first line of the body of the outer for loop, another for loop, is estab lished. A second counter (j) is also initialized to 0, and the body of the inner for loop is executed. On line 17, the chosen character is printed, and control returns to the header of the inner for loop. Note that the inner for loop is only one statement (the printing of the character). The condition is tested (j < columns); if it evaluates to true, j is incremented and the next character is printed. This continues until j equals the number of columns.

When the inner for loop fails its test, in this case after 12 xs are printed, execution falls through to line 18, and a new line is printed. The outer for loop now returns to its header, where its condition (i < rows) is tested. If this evaluates to true, i is incremented and the body of the loop is executed.

In the second iteration of the outer for loop, the inner for loop is started over. Thus j is reinitialized to 0 (!), and the entire inner loop is run again.

The important idea here is that by using a nested loop, the inner loop is executed for each iteration of the outer loop. Thus the character is printed columns times for each row.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.120.200