Lesson 6-2: Count-Controlled Loops
136 | Chapter 6
Name __________________________________________ Date _______________________
Section _________________________________________
Exercise 1: Change program Count so that the number of values to be read (limit) is read from
the keyboard rather than being set as a named constant. Run your program using a value of 9 and
entering the data listed for Prelab Exercise 1. (Don’t forget to prompt for limit.) Your answer
should be the same. If it is not, you have an error.
Run your program again entering a value of your choice for limit, followed by limit integer
values.
_____________ _____________ _____________
Exercise 2: Run program Count entering one fewer data values than called for. What happens?
Explain.
78828_CH06_DaleLab 5/22/09 1:50 PM Page 136
Exercise 3: Run program Count entering one more data value than called for. What
happens? Explain.
Exercise 4: Examine the shell for program SumDigits. When completed, program
SumDigits prompts for and reads a one-digit number, then adds the numbers from
zero to the number, inclusive, and prints the sum.
// Program SumDigits prompts for and reads a one-digit number.
// Values between 0 and the digit (inclusive) are summed.
#include <iostream>
using namespace std;
int main ()
{
int counter; // Loop-control variable
int sum; // Running sum
int digit;
cout << "Enter a one-digit number; press return."
<< endl;
cin >> digit;
counter = /* TO BE FILLED IN */
sum = /* TO BE FILLED IN */
while /* TO BE FILLED IN */
{
/* TO BE FILLED IN */
}
cout << "Sum of digits between 0 and "
<< digit << " is " << sum << endl;
return 0;
}
Looping | 137
78828_CH06_DaleLab 5/22/09 1:50 PM Page 137
Fill in the appropriate initializations and the body of the while loop so that the sum of
the digits from zero through digit (the input value) is computed. Run your program
four times using 0, 3, 7, and 9 as the input values.
Exercise 5: Program Calories in Lesson 5-4 read and printed a string representing a
food item. You had to run the program four times, once for each item. What a waste of
effort! Rewrite the program so that all the processing is done at one time. That is,
enclose the entire program in a count-controlled loop that executes four times. Are