Sams Teach Yourself C++ in 21 Days

(singke) #1

Using do...while................................................................................................


The do...whileloop executes the body of the loop before its condition is tested, thus
ensuring that the body always executes at least one time. Listing 7.7 rewrites Listing 7.6,
this time using a do...whileloop.

LISTING7.7 Demonstrates do...whileLoop
1: // Listing 7.7
2: // Demonstrates do while
3:
4: #include <iostream>
5:
6: int main()
7: {
8: using namespace std;
9: int counter;
10: cout << “How many hellos? “;
11: cin >> counter;
12: do
13: {
14: cout << “Hello\n”;
15: counter--;
16: } while (counter >0 );
17: cout << “Counter is: “ << counter << endl;
18: return 0;
19: }

How many hellos? 2
Hello
Hello
Counter is: 0
Like the previous program, Listing 7.7 prints the word “Hello” to the console a
specified number of times. Unlike the preceding program, however, this program
will always print at least once.
The user is prompted for a starting value on line 10, which is stored in the integer vari-
able counter. In the do...whileloop, the body of the loop is entered before the condi-
tion is tested, and, therefore, the body of the loop is guaranteed to run at least once. On
line 14, the hello message is printed, on line 15 the counter is decremented, and then
finally, on line 16 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 17.
The continueand breakstatements work in the do...whileloop exactly as they do in
the whileloop. The only difference between a whileloop and a do...whileloop is
when the condition is tested.

OUTPUT


186 Day 7


ANALYSIS
Free download pdf