|
|
|
|
|
|
|
It is possible that the body of a while loop will never execute. The while statement checks its condition before executing any of its statements, and if the condition evaluates false, the entire body of the while loop is skipped. Listing 8.6 illustrates this. |
|
|
|
|
|
|
|
|
LISTING 8.6 SKIPPING THE BODY OF THEwhile LOOP |
|
|
|
 |
|
|
|
|
1: // Listing 8.6
2: // Demonstrates skipping the body of
3: // the while loop when the condition is false.
4:
5: #include <iostream.h>
6:
7: int main()
8: {
9: int counter;
10: cout < How many hellos?: ;
11: cin >> counter;
12: while (counter > 0)
13: {
14: cout < Hello!\n;
15: counteró-;
16: }
17: cout < counter is OutPut: < counter;
18: return 0;
19: } |
|
|
|
|
|
|
|
|
How many hellos?: 2
Hello!
Hello!
counter is OutPut:0
How many hellos?: 0
counter is 0 |
|
|
|
|
|
|
|
|
Analysis: The user is prompted for a starting value on line 10, which is stored in the integer variable counter. The value of counter is tested on line 12 and decremented in the body of the while loop. The first time through counter was set to 2, so the body of the while loop ran twice. The second time through, however, the user typed in 0. The value of counter was tested on line 12 and the condition was false; counter was not greater than 0. The entire body of the while loop was skipped, and hello was never printed. |
|
|
|
|
|
|
|
|
What if you want to ensure that hello is always printed at least once? The while loop can't accomplish this, because the if condition is tested before any printing is done. You can force the issue with an if statement just before entering the while: |
|
|
|
|
|