|
|
|
|
|
|
|
if (counter < 1) // force a minimum value
counter = 1; |
|
|
|
|
|
|
|
|
but that is what programmers call a kludge, an ugly and inelegant solution. |
|
|
|
|
|
|
|
|
The dowhile loop executes the body of the loop before its condition is tested, and ensures that the body always executes at least one time. Listing 8.7 demonstrates this program rewritten with a dowhile loop. |
|
|
|
|
|
|
|
|
LISTING 8.7 DEMONSTRATING Adowhile LOOP |
|
|
|
 |
|
|
|
|
1: // Listing 8.7
2: // Demonstrates do while
3:
4: #include <iostream.h>
5:
6: int main()
7: {
8: int counter;
9: cout < How many hellos? ;
10: cin >> counter;
11: do
12: {
13: cout < Hello\n;
14: counter--;
15: } while (counter >0 );
16: cout < counter is: < counter < endl;
17: return 0;
18: } |
|
|
|
|
|
|
|
|
How many hellos? 2
Hello
Hello
counter is: 0 |
|
|
|
|
|
|
|
|
Analysis: The user is prompted for starting a value on line 9, which is stored in the integer variable counter. In the dowhile loop, the body of the loop is entered before the condition is tested, and therefore is guaranteed to be acted on at least once. On line 13 the message is printed, on line 14 the counter is decremented, and on line 15 the condition is tested. If the condition evaluates true, execution jumps to the top of the loop on line 13; otherwise it falls through to line 16. |
|
|
|
|
|
|
|
|
The continue and break statements work in the dowhile loop exactly as they do in the while loop. The only difference between a while loop and a dowhile loop is when the condition is tested. |
|
|
|
|
|