< previous page page_113 next page >

Page 113
while Loops
A while loop causes your program to repeat a sequence of statements as long as the starting condition remains true. In the example of goto, in Listing 8.1, the counter was incremented until it was equal to 5. Listing 8.2 shows the same program rewritten to take advantage of a while loop.
LISTING 8.2while LOOPS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:    // Listing 8.2
2:    // Looping with while
3:
4:    #include <iostream.h>
5:
6:    int main()
7:    {
8:       int counter = 0;               // initialize the condition
9:
10:      while(counter < 5)     // test condition still true
11:      {
12:          counter++;              // body of the loop
13:          cout < counter:  < counter < \n;
14:      }
15:
16:      cout < Complete. counter:  < counter < .\n;
17:      return 0;
18:   }

Output:
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
Complete. counter: 5
Analysis: This simple program demonstrates the fundamentals of the while loop. A condition is tested, and if it is true, the body of the while loop is executed. In this case, the condition tested on line 10 is whether counter is less than 5. If the condition is true, the body of the loop is executed. On line 12 the counter is incremented, and on line 13 the value is printed. When the conditional statement on line 10 fails (when counter is no longer less than 5), the entire body of the while loop (on lines 1114) is skipped. Program execution falls through to line 15.

 
< previous page page_113 next page >

If you like this book, buy it!