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
limit Your Data Sum
_____________ _____________ _____________
Exercise 2: Run program Count entering one fewer data values than called for. What happens?
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 */
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.
Answer for 0: ___________ Answer for 3: ___________
Answer for 7: ___________ Answer for 9 ___________
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
your answers the same with the revised program?
Item Grams of Fat Calories Percent from Fat
Tuna 1 6 ___________
Spaetzle 2 170 ___________
V8 Juice 0 35 ___________
Corned Beef 7 200 ___________
138 | Chapter 6
78828_CH06_DaleLab 5/22/09 1:50 PM Page 138

Get A Laboratory Course in C++, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.