Do-while loops


The do-while loop works just like the while loopalmost. Listing 2.7 shows the difference.

Listing 2.7. Using a do-while loop

 1    #include <iostream> 2    #include <stdlib.h> 3 4    using namespace std; 5 6    int main(int argc, char *argv[]) 7    { 8        int anInt; 9 10       // Prompt the user for an integer. 11       cout << "Please input an integer and press Enter: "; 12 13       // Get the integer. 14     cin >> anInt; 15 16       int i=0; 17       do 18       { 19       cout << i++ << endl; 20       } while (i < anInt); 21 22       system("PAUSE"); 23       return 0; 24  } 

The do-while loop has its test at the end of the loop instead of the beginning. As a result, the program executes the body of the loop first, then performs the test to determine whether it should loop again. Figure 2.10 shows the output of the program in Listing 2.7.

Figure 2.10. The output of a do-while loop.


Figure 2.10 looks the same as Figure 2.8. So what's the difference between a while and a do-while loop? To see the answer, look at Figure 2.11.

Figure 2.11. The do-while loop executes at least once.


If you compare Figure 2.11 to Figure 2.9, you'll see that if the condition of a while loop never evaluates to TRue, the program never executes the body of the while loop. On the other hand, the body of a do-while loop is guaranteed to execute at least once. Because a do-while loop performs its test at the end of the loop instead of the beginning, the body must execute at least once before the condition is ever tested.

Both the while and the do-while loops see a lot of use in all types of programs. There is one more type of loop in C++: the for loop. It's a more complex looping statement, so we'll put off learning about it until the next chapter.

Factoid

Because the while loop performs its test at the beginning of the loop, it is called a pretest loop. Likewise, because the do-while loop performs its test at the end, it is called a posttest loop.




Creating Games in C++(c) A Step-by-Step Guide
Creating Games in C++: A Step-by-Step Guide
ISBN: 0735714347
EAN: 2147483647
Year: N/A
Pages: 148

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