Professional Documents
Culture Documents
Lesson 3 – Repetition
Goal(s):
To follow the loop design strategy to develop loops
To control a loop with the user confirmation or a sentinel value
Minds On…
Analyze the following code. Is count < 100 always true, always false, or
Action …
Key Point
The key to designing a loop is to identify the code that needs to be repeated and write
a condition for terminating the loop.
Writing a correct loop is not an easy task for novice programmers. Consider three
steps when writing a loop.
1. Identify the statements that need to be repeated.
2. Wrap these statements in a loop as follows:
Key Point
It is a common practice to use a sentinel value to terminate the input.
int count = 0;
while (count < 5)
{
//loop body
}
The preceding example executes the loop five times. If you want the user to decide
whether to continue, you can offer a user confirmation. The template of the program
can be coded as follows:
Another common technique for controlling a loop is to designate a special value when
reading and processing a set of values. This special input value, known as a sentinel
value, signifies the end of the input. A loop that uses a sentinel value to control its
execution is called a sentinel-controlled loop.
The following program reads and calculates the sum of an unspecified number of
integers. The input 0 signifies the end of the input. Do you need to declare a new
variable for each input value? No. Just use a variable named data (line 8) to store the
input value and use a variable
Introduction to Computer Science 11 3
named sum (line 12) to store the total. When a value is read, assign it to data
(lines 9, 20) and add it to sum (line 15) if it is not zero.
Assessment
1. What will be displayed when the following code is executed?
3
Introduction to Computer Science 11
Programming Exercise(s)
4. (Math tutor) Write a program that displays a menu as shown in the sample
run.
You can enter 1, 2, 3, or 4 for choosing an addition, subtraction, multiplication, or
division test. After a test is finished, the menu is redisplayed. You may choose
another test or enter 5 to exit the system. Each test generates two random
singledigit numbers to form a question for addition, subtraction, multiplication, or
division. For a subtraction such as number1 – number2, number1 is greater than
or equal to number2. For a division question such as number1 / number2,
number2 is not zero.
3
Introduction to Computer Science 11