Iteration Statements

 < Day Day Up > 



Selection statements like if and switch are required to give your programs decision making capability, however, once through the selection statement that is it! Sometimes you want to do things over and over again either forever or at least until something happens to break the loop. This is where iteration statements come into the picture.

In this section I will discuss the while, do, and for statements. Each statement gives you the ability to perform one or more operations repeatedly. Your choice of which iterative statement to use depends on what needs to be done.

while Statement

Figure 6-4 shows a diagram of a while statement. The while statement will evaluate the condition before executing the associated statement. As indicated in figure 6-4, the statement may never execute if the condition is always false.

click to expand
Figure 6-4: while Statement Diagram

Once inside the body of the while loop the condition must eventually evaluate to false or the loop will execute forever. In many programming situations you want to loop forever until the program exits from within the body of the loop. An example of this would be a menu-processing while loop. I will show you an example of this below, but for now, take a look at a simple while statement:

Listing 6.12: while statement

start example
1  int count = 0; 2 3  while(count++ < 5){ 4     cout<<"Count = : "<<count<<endl; 5     }
end example

One line 1 the integer variable count is declared and initialized. The condition expression involves the use of two operators. First, the less than comparison is made followed by the postfix increment. When first compared, the variable count is zero, the body of the while loop is entered, and the statement on line 4 executes. What values of count will print to the screen?

In this case, the postfix increment is evaluated prior to entry into the body of the loop. The first value to be printed to the screen is one. This while loop will execute five times. The following while loop behaves somewhat differently:

Listing 6.13: while statement

start example
1  int count = 0; 2 3  while(++count < 5){ 4     cout<<"Count = : "<<count<<endl; 5     }
end example

In this example the prefix operator increments the value of count before the less than expression is evaluated. The first value of count to print to the screen is still one but the loop executes only four times. The lesson here is clear: Be sure you understand the effects operators have on your expressions.

Controlling while Statements with Sentinel Values

In most instances you won’t know how many times a while loop should execute. In these situations you can employ sentinel values. A sentinel value is simply a value, in most cases arbitrary, of your choosing, that when used in the condition expression of the while loop forces the loop to exit. Sentinel values can be set based upon some condition in the body of the while loop, or, they can be entered via the keyboard. Examine the following code:

Listing 6.14: use of sentinel value

start example
1  float total = 0, average = 0, input = 0;  2  int count = 0;  3  4  while(input >= 0){  5  6  cout<<"Please enter a positive number to average "  7      <<" or negative number to exit: ";  8  cin>>input;  9 10  if(!cin){ 11      cin.clear(); 12      cin.ignore(INT_MAX, '\n'); 13   }else if(input >= 0){ 14     total += input; 15     average = (total/(++count)); 16     cout<<"The average is: "<<average<<endl; 17     } 18  }//end while
end example

In this example the while loop condition will evaluate to true so long as the number entered is positive. Any negative number will cause the while loop condition to evaluate to false thus exiting the loop. This code also shows an if- else statement being used in the body of a while loop. On line 10 the cin object is examined for failure. If the cin object fails it means the wrong input type was entered. If the cin object was successful the else statement on line 13 is executed. The else statement includes another if statement that checks to make sure a positive number was entered. If so the averaging calculation is performed, otherwise, the calculation is skipped.

In this case the sentinel value is any negative number. So long as the number entered is greater than or equal to zero the while loop will repeat. A negative number will terminate execution of the while loop.

Nesting while Statements

While statements can be nested just like their if-else cousins. The following code offers an example:

Listing 6.15: nested while statements

start example
1  bool done = false;  2  int inner_count = 0, outer_count = 0;  3  4  while(!done){  5     while(inner_count < 3){  6       cout<<"Inner count is: "<<inner_count++<<endl;  7     }  8      if(outer_count++ > 3){  9        done = true; 10      } 11 12  inner_count = 0; 13  }
end example

In this example, the outer loop is controlled by a boolean sentinel value which is set to false prior to entry into the loop and subsequently set to true in the body of the outer loop via the if statement on line 8. The inner while loop will execute until the variable inner_loop becomes greater than three, at which time the inner loop terminates. The outer_count variable is compared to three and then incremented. If outer_count is less than three the variable done remains false, inner_count is reset to zero, and the outer while loop executes again. When outer_count is greater than three done is set to true causing the outer loop to terminate.

Doing Something Forever

While statements are often used without sentinel values to indefinitely repeat an operation, leaving the proper exiting of the program to some statement within the body of the while loop. The idiomatic way of writing a while loop so that it repeats forever is shown in the following example:

Listing 6.16: looping forever

start example
1  while(true){ 2      //repeat what's in here forever 3  }
end example

The condition of the while loop is simply the boolean literal value true. Alternatively the statement can be written in the following manner...

Listing 6.17: looping forever

start example
1  while(1){ 2      //repeat this stuff too! 3  }
end example

...although I don’t recommending doing so!

Exiting While Loops with the break Statement

The important thing to remember when using forever-repeating while loops is they must be explicitly exited by the programmer. One way to exit a while loop is with the break statement. Examine the following source code:

Listing 6.18: nested while loop

start example
 1   int inner_loop = 0, outer_loop = 0;  2  3  while(outer_loop++ < 3){  4  5   cout<<"Outer loop = "<<outer_loop<<endl;  6     while(true){  7      if(inner_loop++ < 3)  8        cout<<"Inner loop = "<<inner_loop<<endl;  9        else break; 10      } 11  }
end example

This example shows nested while loops. The inner while loop, starting on line 6, will repeat forever until the if statement’s condition on line 7 evaluates to false, at which time the break statement will be executed exiting the inner loop. Since the variable inner_loop is not reset to zero the inner loop executes only once.

A break exits its immediate enclosing iteration statement. In example 6.18 above, the break statement is part of an if-else statement, which itself is contained within a while loop. Since the inner while loop contains the break it is the one exited when the break statement is executed.

You can also exit the entire program from a while loop using the exit() function. The following extended example shows how a forever-repeating while loop can be used to continuously execute a switch statement that processes keyboard input. The program terminates when the letter q or Q is entered.

Listing 6.19: switch inside of while loop

start example
  1  char input = ' ';   2   3  while(true){   4       cout<<"Enter a character: ";   5       cin>>input;   6   7      switch(input){   8   9        case 'a':  10        case 'A': cout<<"You entered "<<input<<"!"<<endl;  11                break;  12  13        case 'b':  14        case 'B': cout<<"You entered "<<input<<"!"<<endl;  15                break;  16  17        case 'c':  18        case 'C':cout<<"You entered "<<input<<"!"<<endl;  19                break;  20  21        case 'd':  22        case 'D':cout<<"You entered "<<input<<"!"<<endl;  23                break;  24  25        case 'e':  26        case 'E':cout<<"You entered "<<input<<"!"<<endl;  27                break;  28  29        case 'f':  30        case 'F':cout<<"You entered "<<input<<"!"<<endl;  31                break;  32  33        case 'g':  34        case 'G':cout<<"You entered "<<input<<"!"<<endl;  35                break;  36  37        case 'h':  38        case 'H':cout<<"You entered "<<input<<"!"<<endl;  39                break;  40  41        case 'i':  42        case 'I':cout<<"You entered "<<input<<"!"<<endl;  43                break;  44  45        case 'j':  46        case 'J':cout<<"You entered "<<input<<"!"<<endl;  47                break;  48  49        case 'k':  50        case 'K':cout<<"You entered "<<input<<"!"<<endl;  51                break;  52  53        case 'l':  54        case 'L':cout<<"You entered "<<input<<"!"<<endl;  55                break;  56  57        case 'm':  58        case 'M':cout<<"You entered "<<input<<"!"<<endl;  59                break;  60  61        case 'n':  62        case 'N':cout<<"You entered "<<input<<"!"<<endl;  63                break;  64  65        case 'o':  66        case 'O':cout<<"You entered "<<input<<"!"<<endl;  67                break;  68  69        case 'p':  70        case 'P':cout<<"You entered "<<input<<"!"<<endl;  71                break;  72  73        case 'q':  74        case 'Q':cout<<"You entered "<<input<<"!"<<endl;  75                cout<<"Goodbye!";  76                exit(EXIT_SUCCESS);  77  78        case 'r':  79        case 'R':cout<<"You entered "<<input<<"!"<<endl;  80                break;  81  82        case 's':  83        case 'S':cout<<"You entered "<<input<<"!"<<endl;  84                break;  85  86        case 't':  87        case 'T':cout<<"You entered "<<input<<"!"<<endl;  88                break;  89  90        case 'u':  91        case 'U':cout<<"You entered "<<input<<"!"<<endl;  92                break;  93  94        case 'v':  95        case 'V':cout<<"You entered "<<input<<"!"<<endl;  96                break;  97  98        case 'w':  99        case 'W':cout<<"You entered "<<input<<"!"<<endl; 100                break; 101 102        case 'x': 103        case 'X':cout<<"You entered "<<input<<"!"<<endl; 104                break; 105 106        case 'y': 107        case 'Y':cout<<"You entered "<<input<<"!"<<endl; 108                break; 109 110        case 'z': 111        case 'Z':cout<<"You entered "<<input<<"!"<<endl; 112                break; 113 114        default: cout<<"Character not part of alphabet!"<<endl; 115                break; 116     } //end switch 117 }// end while
end example

do Statement

click to expand
Figure 6-5: do Statement Diagram

The do statement differs from the while statement in the position of the condition test. In the while statement the condition test took place before the loop was executed. This resulted in a possibility of the while loop never executing the body of the loop. The do statement tests the condition after the body of the loop. This results in the body of the do loop executing at least once.

Figure 6-5 shows a diagram of the do statement. The following source code shows a do statement in action:

Listing 6.20

start example
1 int count = 0; 2 3 do { 4   cout<<"Count ="<<count<<endl; 5   }while(count++ < 3);
end example

Nesting do Statements

Do statements can be nested in exactly the same way as while statements.

for Statement

There is often a need in programming to repeat a series of steps a known amount of times. You can do this with the while statement or the do statement and you have seen it done several times already in this chapter. To make a while or do statement iterate for a specified number of loops you must perform the following general steps:

Step 1 - Declare an integer variable with which to keep count of the number of loops,

Step 2 - Initialize the counting variable declared in step one (step one and two can be combined into one statement),

Step 3 - Test the condition,

Step 4 - Perform the statement or statements in the body of the statement if condition is true,

Step 5 - Increment the loop counting variable,

Step 6 - Repeat steps 3 through 5 until the condition evaluates to false.

The following example shows a while statement with steps 1 through 5 labeled:

Example 6.21: while loop behaving like for loop

start example

click to expand

end example

The for statement provides a convenient format for performing steps 1, 2, 3, and 5, as shown in figure 6-6.

click to expand
Figure 6-6: for Statement Diagram

The following source code shows a for statement in action:

Listing 6.22: for statement

start example
 1 for(int i = 0; i<3; i++){ 2    cout<<"I equals = "<<i<<endl; 3 }
end example

On line one, the variable i is being declared and initialized for the purpose of loop counting. The condition is tested and, if true, the body of the for statement is performed, and i is incremented. The scope of the variable i is local to the body of the for statement and is visible to any enclosing scopes. Examine the following code:

Listing 6.23: for loop scope

start example
 1 for(int i = 0; i<3; i++){ 2    cout<<"I equals = "<<i<<endl; 3 } 4 int i = 0;
end example

On line four another variable i is being declared and defined. This is legal because the i declared in the for statement initialization section on line one is visible only in the body of the for statement.

I’d like to point out that example 6.22 illustrates the idiomatic way of writing a for statement. Writing the for statement in the idiomatic way makes your source code easier to read and comprehend.

For statements are an ideal way to implement summations in source code. Example 6.24 implements the following summation:

Listing 6.24: implementing summation

start example
1 for(int i = 1, total = 0; i<=100; i++){ 2     total += i; 3     cout<<"i = "<<i<<" "; 4     cout<<"Total = "<<total<<endl; 5 }
end example

Note on line one how the variable total is declared and initialized in the for statement initialization section as well as the variable i.

Nesting for Statements

For statements can be nested like the while and do-while statements. The following code gives an example:

Listing 6.25: nesting for statements

start example
1 for(int i = 0; i<3; i++){ 2    cout<<"i = "<<i<<endl; 3     for(int j = 0; j<3; j++){ 4       cout<<"j = "<<j<<endl; 5     } 6 }
end example

When nesting for loops you have to be especially aware of variable scoping within each for loop’s body block. In this example, the variable i is in scope for the outer loop as well as the inner loop. Most times, however, a separate counting variable is required to keep track of enclosed nested loop iterations. The variable j is declared in the for loop on line 3 for this purpose.

Nesting for loops in this fashion results in the inner loop being executed each time the outer loop is executed.

break

The break statement can be used to terminate for loops. The break statement exits its enclosing loop. Examine the following source code:

Listing 6.26: break statement

start example
1 for(int i = 0; i<3; i++){ 2     cout<<"i = "<<i<<endl; 3     for(int j = 0; j<3; j++){ 4        cout<<"j = "<<j<<endl; 5        if(j == 1) 6          break; 7     } 8 }
end example

This code is similar to example 6.25 with the addition of the if statement on line 5. If the variable j, which is visible only in the body of the inner for statement, is equal to 1, then the inner loop will terminate and control will be passed to the outer for statement.

Doing Something Forever with a for Statement

A for statement can also be used to perform an operation repeatedly forever. The following code shows how this is done:

Listing 6.27: looping forever

start example
1 for(;;){ 2    //do this forever 3 }
end example

continue

The continue keyword can be used with while, do, and for statements to pass control to the end of the loop. Here’s an example:

Listing 6.28: continue statement

start example
1 char ch = ' ';  2 int count = 0;  3  4 cout<<"Enter characters or numbers: "<<endl;  5  6 while(cin>>ch){  7    if((ch >= '0') && (ch <= '9')){  8    continue;  9    } 10 11    cout<<"Count is "<<++count<<" and the character is "; 12    cout<<ch<<endl; 13 14    if(ch == 'q'){ 15    cout<<"Goodbye!"<<endl; 16    break; 17    } 18 }
end example

This while loop will repeat as long as characters are input via the keyboard or until the q character is entered. If a 0 through 9 is entered the continue statement on line 8 causes any statements appearing on lines 9 through 17 to be skipped.

Avoiding break and continue

Use break and continue statements sparingly. Their overuse leads to hard-to-understand code and dang-near- impossible-to-detect programming errors. Break is used mostly in switch statements, otherwise, there is usually a more elegant way of rewriting code that avoids break and continue. The ability to write elegant code comes from experience.



 < Day Day Up > 



C++ for Artists. The Art, Philosophy, and Science of Object-Oriented Programming
C++ For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504028
EAN: 2147483647
Year: 2003
Pages: 340
Authors: Rick Miller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net