Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 185

7


7: int main()
8: {
9: int counter;
10: std::cout << “How many hellos?: “;
11: std::cin >> counter;
12: while (counter > 0)
13: {
14: std::cout << “Hello!\n”;
15: counter--;
16: }
17: std::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 OutPut: 0
The user is prompted for a starting value on line 10. This starting value is stored
in the integer variable counter. The value of counteris tested on line 12 and
decremented in the body of the whileloop. In the output, you can see that the first time
through,counterwas set to 2 , and so the body of the whileloop ran twice. The second
time through, however, the 0 was entered. The value of counterwas tested on line 12
and the condition was false; counterwas not greater than 0. The entire body of the
whileloop was skipped, and Hellowas never printed.
What if you want to ensure that Hellois always printed at least once? The whileloop
can’t accomplish this because the ifcondition is tested before any printing is done. You
can force the issue with an ifstatement just before entering the whileloop
if (counter < 1) // force a minimum value
counter = 1;
but that is what programmers call a “kludge” (pronounced klooj to rhyme with stooge),
an ugly and inelegant solution.

OUTPUT


LISTING7.6 continued


ANALYSIS
Free download pdf