Loops in the Everyday World
You may notfirst step, you had to figure out how to execute this process: you were one year old.
With your
remember it, but you probably learned to walk about the time
Put one foot in front of the other
At some point, you did just that, and it was a major accomplishment. Of course, this didn't get
you very far. If you wanted to walk across the room, you needed to extend this process to:
Put one foot in front of the other
Put one foot in front of the other
Put one foot in front of the other
And so on.
This is not a very efficient way to describe what you did; a detailed list of your actions as you
ambled all over the house would get very long. Since you did the same thing over and over, a
much better way to describe your actions would be:
Repeat
Put one foot in front of the other
Until you get across the room
This way is short, convenient, and just as descriptive. Even if you want to take hundreds or
thousands of steps, the process can still be described in just three lines. This is the basic idea of
a loop.
Walking is just one of many examples of loops in your daily life. For example, if you have a
large family and need to prepare lunches for everyone in the morning, you can do this:
Repeat
Make a sandwich
Wrap the sandwich
Place the sandwich in a lunch bag
Place an apple in the lunch bag
Place a drink in the lunch bag
Until 7 lunches have been made
Where else would you encounter a looping process? How about in balancing your checkbook
(one check at a time), or while brushing your teeth, or even when playing a compact disc song by
song? After you read this chapter (one word at a time), you'll be ready to place loops in your
programs as well.
ISBN: 0-536-12326-8
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
1 CHAPTER FOUR 2
Repetition Structures: Looping
In this chapter, we will explore the topic of loops, or repetition structures, which con-
tain a block of statements that can be executed repeatedly. We will discuss differ-
ent types of loops, applications of loops, and using loops contained in other loops.
To be more specific, you will learn about
1. The difference between pre-test and post-test loops [Section 4.1].
2. How to use relational and logical operators in loop conditions [Section 4.1].
3. Constructing counter-controlled loops [Section 4.2].
4. Constructing sentinel-controlled loops [Section 4.3].
5. Some applications of loops, including data input and validation, and comput-
ing sums and averages [Section 4.3].
6. Using nested loops [Section 4.4].
ISBN: 0-536-12326-8
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
4.1 3 An Introduction to Repetition provide statements to create a loop (or rep-
All programming languages
Structures
etition structure)--a block of code that, under certain conditions, will
be executed repeatedly. In this section, we will introduce some basic
ideas about these structures.
4 A Simple Example of a Loop
We start with a simple example of a loop.
EXAMPLE 1 This program segment repeatedly inputs a number
from the user and displays that number until the user
enters 0. The program then displays the word Done.
Repeat Input
Prompt for and input a number, Num Num
Write Num
Until Num = 0
Write "Done"
Write
In this pseudocode, the loop begins with the word Num
Repeat and ends with the line containing the word
Until. The body of the loop--the block of state-
ments that will be executed repeatedly--consists Is
of the statements between Repeat and Until. The Num = 0?
body of the loop is executed until the test condi-
tion following the word Until becomes true (in No
Yes
this case, until the number input by the user is 0).
At that point, the loop is exited, and the statement Write
that follows the loop is executed. A flowchart for "Done"
this program is shown in Figure 1.
Let us trace (follow) execution of this program, FIGURE 1
assuming that the user enters the numbers 1, 3, Flowchart for Example 1
and 0, in that order:
1 When execution begins, the loop is entered, the number 1 is input,
and this number is displayed. These actions make up the first pass
(time) through the loop. The test condition, Num = 0 , is now "tested"
and found to be false (because, at this point, Num = 1), which caus-
es the loop to be reentered--the body of the loop is executed again.
1 On the second pass through the loop, the number 3 is input and dis-
played, and once again the condition Num = 0 is false, causing anoth-
er pass through the loop to take place.
1 On the third pass through the loop, the number 0 is input and dis-
played. This time, the condition Num = 0 is true, so the loop is exit-
ed--execution transfers to the statement after the loop (Write "Done" ).
1 The word Done is displayed, and the program is complete.
ISBN: 0-536-12326-8
96 3 CHAPTER 4 Repetition Structures: Looping
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Beware of Infinite Loops If a loop's test condition is never satisfied (in the
TIP case of a Repeat ... Until loop, if the condition never becomes true), then the
loop will never be exited--it will become an infinite loop. It is therefore impor-
tant to make clear, through a suitable prompt, how the user is to terminate
the action of the loop. In Example 1, a suitable prompt would be:
Write "Enter a number; enter 0 to quit."
Relational and Logical Operators 4
The "condition" that determines whether a loop is reentered or exited is
usually constructed with the help of relational and logical operators. We
will briefly discuss these operators here; this topic is covered in more
depth in Section 3.2.
Relational operators Here are the six standard relational operators
and the programming symbols we will use in this book to represent them:
equal to, = not equal to, <>
less than, < less than or equal to, <=
greater than, > greater than or equal to, >=
All six operators can be applied to either numeric or character string
data. In particular, this is the way these operators work with strings:
1 Two strings are equal if they contain exactly the same characters in
the same order. Otherwise, they are not equal.
1 If the two strings to be compared represent proper names (and thus
consist solely of letters), then alphabetical order determines the effect
of the operators <, <=, >, and >=. To be more specific, if Name1 and
Name2 represent proper names:
Name1 < Name2 if Name1 precedes Name2 under alphabetical
ordering.
Name1 > Name2 if Name1 follows Name2 under alphabetical
ordering.
Name1 <= Name2 if Name1 < Name2 or Name1 = Name2
Name1 >= Name2 if Name1 > Name2 or Name1 = Name2
For example, if Num = 3 and Name = "Joe" then the condition:
1 Num <> 1 is true because 3 is not equal to 1.
1 Name = "joe" is false because uppercase letters (like J) are different
characters from lowercase letters (like j).
1 Name <> " Joe" is true because blanks are characters, so these two
strings do not contain the same characters.
1 Name >= "Jo" is true because "Joe" follows "Jo" under alphabetical
order.
ISBN: 0-536-12326-8
4.1 An Introduction to Repetition Structures 4 97
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Logical operators The three basic logical operators, Or, And, and
Not, are used to create more complicated (compound) conditions from
given simple conditions. If S1 and S2 are conditions (such as Num <= 0
or Response = "Y" ) then the compound condition:
1 S1 Or S2 is true if either S1 is true or S2 is true (or both); it is false if
both S1 and S2 are false.
4 1 S1 And S2 is true if both S1 and S2 are true; it is false if either S1 or S2
is false.
1 Not S1 is true if S1 is false; the condition is false if S1 is true.
For example, If Num = 3 and Name = "Joe", then:
1 (Num = 1) Or (Name = "Joe") is true but (Num = 1) And (Name = "Joe") is
false, because one of the simple conditions (Num = 1) is false, while
the other is true.
1 Not ((Num = 1) Or (Name = "Joe")) is false, because (Num = 1) Or (Name =
"Joe") is true.
Pre-test and Post-test Loops
All repetition structures can be divided into two fundamental types: pre-
test loops and post-test loops. The loop in Example 1,
Repeat
Prompt for and input a number, Num
Write Num
Until Num = 0
is an example of a post-test loop--one in which the test condition occurs
after the body of the loop is executed. In a pre-test loop, on the other
hand, the test condition appears at the top of the loop.
EXAMPLE 2 This is an example of a pre-test loop:
While Num <> 0
Write Num
Input Num
End While
In our pseudocode for a pre-test loop: the first statement begins with the
word While and is followed by the test condition (here, Num <> 0 --Num
"not equal to" 0); the last statement in the loop is End While . As with post-
test loops, all statements in between comprise the body of the loop. When
the loop is entered, the test condition is evaluated. If it is found to be
true, the body of the loop is executed and control then returns to the top
of the loop; if it is false, then the loop is exited and the statement fol-
lowing End While is executed next.
ISBN: 0-536-12326-8
98 3 CHAPTER 4 Repetition Structures: Looping
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Suppose that in this example, the value of Num is 1 when the loop is
entered and that, on the next two passes through the loop, the user enters
the numbers 3 and 0. Here's how execution flows in this case:
1 The While statement is executed testing the test condition, Num <> 0 ,
which is found to be true (Num is initially equal to 1). Thus, the body
of the loop is executed, 1 is displayed, and 3 is input. Then, control
returns to the top of the loop.
1 Again, the test condition is evaluated, and since 3 is not equal to 0, a
second pass is made through the loop. This time 3 is displayed and 0
4
is input, before control returns to the top of the loop.
1 Once again, the test condition is evaluated, and since Num is now
equal to 0, it is found to be false. The loop is therefore exited and the
statement following End While is executed next.
The flow of execution for the program of Example 2 is illustrated
under "pre-test loop" in Figure 2, which shows typical pre-test and post-
test loops.
FIGURE 2 Pre-test Loop Post-test Loop
Pre-test and
Post-test Loops
Is exit
No
condition Execute
true? loop body
Yes
Execute Is exit
Execute
statement condition
loop body No
after loop true?
Yes
Execute
statement
after loop
ISBN: 0-536-12326-8
4.1 An Introduction to Repetition Structures 4 99
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Differences There are several basic differences between pre-test and post-test loops:
between pre-test
and post-test 1 By definition, a pre-test loop has its test condition--the one that deter-
loops mines whether or not the body of the loop is executed--at the top; a
post-test loop has its test condition at the bottom.
1 The body of a post-test loop is always executed at least once. The
body of a pre-test loop will not be executed at all, however, if its test
4 condition is false on the first pass.
1 Before a pre-test loop is entered, the variables that appear in its test
condition must be initialized--they must be assigned a value. This is
not necessary in a post-test loop; here, the test condition variables
may be initialized within the body of the loop. For example, the fol-
lowing program segment uses a pre-test loop to display the squares of
numbers input by the user until he or she enters zero or a negative
number (which is not displayed).
Input Number
While Number > 0
Write Number ^ 2
Input Number
End While
Notice that we initialize the variable Number by using an Input state-
ment just prior to entering the loop. (Trace this pseudocode with the
test data 3, 1, 1 to see in detail how it works.)
Either a pre-test loop or a post-test loop can be used to accomplish a giv-
en task, although, as you will discover, some tasks are easier to accom-
plish with pre-test loops; others with post-test loops.
Indent the Body of a Loop To make it easier to read your pseudocode (and
STYLE POINTER the corresponding program code), you should indent the body of a loop rel-
ative to its first and last statements. For example, compare the loop on the
right, which is indented, to that on the left, which is not:
Not indented: Repeat Indented: Repeat
Input Num Input Num
Write Num Write Num
Until Num = 0 Until Num = 0
Reading Check 4.1
1. What numbers will be displayed if code corresponding to the
following pseudocode is run:
a. Set Num = 1 b. Set Num = 1
Repeat While Num < 3
Write 2 * Num Write 2 * Num
Set Num = Num + 1 Set Num = Num + 1
Until Num = 3 End While
ISBN: 0-536-12326-8
100 3 CHAPTER 4 Repetition Structures: Looping
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
2. Is each of the following conditions true or false?
a. 5 = 5 c. 5 < 5 e. 5 > 5
b. 5 <> 5 d. 5 <= 5 f. 5 >= 5
3. If C1 = "Jo" and C2 = "jo", is each of the following true or false?
a. C1 > "Al" d. (C1 = "Jo") And (C2 = "Mo")
b. C1 = "Jo " e. (C1 = "Jo") Or (C2 = "Mo")
c. C1 <= "Joe" f. Not(C1 = C2)
4. List the main differences between pre- and post-test loops. 4
5. The following program is supposed to input numbers from the user
and display them as long as 0 is not entered. A statement is missing;
insert the missing statement.
Input Number
While Number <> 0
Write Number
End While
4.2 3 Counter-controlledwe discussed two fundamental types of repetition struc-
In Section 4.1,
Loops
tures, pre-test and post-test loops. In this section, we will discuss a spe-
cial type of pre-test loop known as a counter-controlled loop. A
counter-controlled loop is one that is executed a fixed number, N, of
times, where N is known prior to entering the loop for the first time.
Constructing a Counter-controlled Loop
A counter-controlled loop is so-named because it contains a variable (the
counter) that keeps track of the number of passes through the loop (the
number of loop iterations). When the counter reaches a preset number,
the loop is exited.
EXAMPLE 3 One common use of counter-controlled loops is to print "tables" of data. For
example, suppose we want to display the squares of the first N positive
integers, where N is to be entered by the user. The pseudocode for this
process is:
Prompt for and input the positive integer N
Initialize the counter to 1: Set Count = 1
While Count <= N
Write Count, Count ^ 2
Add 1 to Count: Set Count = Count + 1
End While
Notice that to ensure that the counter Count correctly keeps track of the
number of loop iterations:
ISBN: 0-536-12326-8
4.2 Counter-controlled Loops 4 101
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
1 We set Count equal to its first value--we initialize it to 1--before
entering the loop.
2 We increment (increase) Count by 1 within the loop.
Thus,
1 On the first pass through the loop, the number 1 and its square are
displayed, and Count is incremented to 2.
4 1 On the second pass through the loop, the number 2 and its square are
displayed, and Count is incremented to 3.
This process continues until
1 On the Nth pass through the loop, N and its square are displayed, Count
is incremented to N + 1, and the loop is exited because the value of
Count now exceeds N.
A flowchart corresponding to this pseudocode is shown in Figure 3.
FIGURE 3
Flowchart for Input
Example 3 N
Set
Count = 1
Is No
Count <= N
?
Yes
Display
Count,
Count ^ 2
Add 1
to Count
ISBN: 0-536-12326-8
102 3 CHAPTER 4 Repetition Structures: Looping
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Built-in Counter-controlled Loops
Most programming languages contain a statement that makes it easy to con-
struct a counter-controlled loop. We will use the following pseudocode to
represent this statement, which creates a "built-in" counter-controlled loop:
For Counter = InitialValue Step Increment To LimitValue
body of the loop
End For
In this typical For statement, Counter must be a variable, Increment must
4
be a constant (a number), and InitialValue and LimitValue may be con-
stants, variables, or expressions. For example, in the statement
For K = 1 Step 3 To N + 1
the counter is the variable K, the initial value is the constant 1, the incre-
ment is the constant 3, and the limit value is the expression N + 1.
The action of a A For loop works like this:
For loop
1 Upon entering the loop, Counter is set equal to InitialValue and, if
InitialValue is not greater than LimitValue, then the body of the loop
is executed. If Counter is greater than LimitValue, the loop is skipped--
the statement following End For is executed next.
1 On each pass through the loop, Counter is increased by the value of
Increment and, if the new value of Counter is not greater than
LimitValue, the body of the loop is executed again. When the value
of Counter exceeds that of LimitValue, the loop is exited and the state-
ment following End For is executed next.
A flowchart depicting the action of a For loop is shown in Figure 4.
FIGURE 4
The Action of a Set Counter =
InitialValue
For Loop
Is
Counter <= No
LimitValue
?
Yes
Execute
body of loop
Set Counter =
Counter +
Increment
ISBN: 0-536-12326-8
4.2 Counter-controlled Loops 4 103
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
EXAMPLE 4 The following For loop has the same effect as the While loop we con-
structed in Example 3 at the beginning of this section--it displays a table
of numbers from 1 to N and their squares.
Prompt for and input a positive integer N
For Count = 1 Step 1 To N
Write Count, Count ^ 2
4 End For
Here are a few more examples that illustrate additional features of
For loops.
EXAMPLE 5 This program provides an example of a For loop with an increment value
that is not equal to 1. It displays the odd numbers between 1 and 20.
For N = 1 Step 2 To 20
Write N
End For
On the first pass through this loop, N is initialized to 1, displayed, and incre-
mented by 2 (due to Step 2 in the For statement). Thus, on the second pass,
3 is displayed and N is incremented by 2 again. This continues until the
10th pass. On this loop iteration, the value of N (19) is displayed and incre-
mented to 21. Since N now exceeds the limit value (20), the loop is exited.
EXAMPLE 6 By using a negative value for the loop increment, we can "step backwards"
through a loop; that is, have the counter variable decrease in value from iter-
ation to iteration. For a negative increment, the loop is exited when the val-
ue of the counter becomes less than the loop's limit value. Here's an example:
For Index = 9 Step 2 To 5
Write Index
End For
In the first pass through this loop, Index is initialized to 9, this value is dis-
played, and then 2 (the increment) is added to it. The value of Index is
now 7. On the second pass, 7 is displayed and Index is decreased to 5.
Finally, on the third pass, 5 is displayed and Index is set equal to 3. Since
3 is less than the limit value (5), the loop is exited.
EXAMPLE 7 If the loop increment is positive and the initial value is greater than the lim-
it value, then the body of the loop is skipped.
Write "Before loop"
For K = 5 Step 1 To 4
Write "Help, I'm a prisoner in a For loop!"
End For
Write "After loop"
ISBN: 0-536-12326-8
104 3 CHAPTER 4 Repetition Structures: Looping
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Since the initial value (5) is greater than the limit value (4) and the incre-
ment is positive (it is 1), the body of the loop is skipped. Thus, the output
produced by code corresponding to this pseudocode is:
Before loop
After loop
Note that a For loop is also skipped when the increment is negative if
the initial value is less than the limit value.
4
Reading Check 4.2
1. What numbers will be displayed when code corresponding to the
following pseudocode is run:
a. Set N = 3 b. For K = 10 Step 2 To 7
For K = N Step 1 To N + 2 Write K
Write N, " ", K End For
End For
2. What output will be displayed when code corresponding to the
following pseudocode is run:
a. Set N = 3 b. For K = 1 Step 1 To 3
For K = 5 Step 1 To N Write "Hooray"
Write N End For
End For
3. Write a program (pseudocode) that contains the statement
For Count = 1 Step 1 To 3
and which would produce the following output if it were coded and run:
10
20
30
4. Rewrite the following pseudocode using a For loop instead of the
While loop shown here.
Set Num = 1
While Num <= 10
Input Response
Write Response
Set Num = Num + 1
End While
4.3 3 Applications of the rest of the book, you will see many examples of how the
Throughout
Repetition Structures
repetition (or loop) structure can be used in constructing a program. In this
section, we will present a few basic applications of this control structure.
ISBN: 0-536-12326-8
4.3 Applications of Repetition Structures 4 105
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Using Sentinel-controlled Loops to Input Data
Loops are often used to input large amounts of data: on each pass through
the loop, one item of data (or one set of data) is entered into the pro-
gram. The test condition for such a loop must cause it to be exited after
all data have been input. Often, the best way to force a loop test is to
have the user enter a special item, a sentinel value, to act as a signal
4
that input is complete. The sentinel item, or end-of-data marker, should
be chosen so that it cannot possibly be mistaken for actual input data.
For example, if a list of positive numbers is to be input, the sentinel value
could be chosen to be the number 1. Here is a simple example of a sentinel-
controlled loop, one that uses a sentinel value to determine whether or
not the loop is to be exited.
EXAMPLE 8 Suppose that the input data for a program that computes employee salaries
consists of the number of hours worked by each employee and his or her
rate of pay. The following pseudocode could be used to input and process
this data:
Prompt for and input the number of hours worked (Hours)
While Hours <> 1
Prompt for and input the rate of pay (Rate)
Set Salary = Hours * Rate
Write Hours, Rate, Salary
Prompt for and input Hours
End While
It is crucial that the input prompts for the number of hours worked (one
prompt prior to the loop, one within the loop) make it clear to users that
they must enter the number 1 when all employees have been processed.
Thus, a refinement of this pseudocode would be:
Write "Enter the number of hours worked."
Write "Enter 1 when you are done."
Input Hours
While Hours <> 1
Write "Enter the rate of pay."
Input Rate
Set Salary = Hours * Rate
Write Hours, Rate, Salary
Write "Enter the number of hours worked."
Write "Enter 1 when you are done."
Input Hours
End While
In this program segment, if the value input for Hours is the sentinel val-
ue 1, the test condition in the While statement is false, the loop is exit-
ed and input is terminated. Otherwise the loop body is executed, inputting
ISBN: 0-536-12326-8
106 3 CHAPTER 4 Repetition Structures: Looping
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Rate, computing and displaying the salary, and again inputting Hours.
Then, the process is repeated.
EXAMPLE 9 Another way to allow the user to signal that all data have been input is to
have the program ask, after each input operation, whether or not this is
the case. This technique is illustrated in the following program segment.
Repeat
Write "Enter the number of hours worked."
Input Hours
4
Write "Enter the rate of pay."
Input Rate
Set Salary = Hours * Rate
Write Hours, Rate, Salary
Write "Process another employee? (Y or N)"
Input Response
Until Response = "N"
Here, the user enters the letter Y if there are more data to input, or N oth-
erwise. (Hence, the variable Response must be of character or string
type.) The test condition, Response = "N" , then determines whether or
not the loop is reentered.
Data Validation
To have the user enter a positive number at some point during program
execution, we use pseudocode similar to the following:
Write "Enter a positive number: "
Input Num
However, despite the input prompt, the user might enter a negative num-
ber or zero, which may in turn cause an error when the program is run.
To ensure that this does not occur, you should include statements in the
program that check, or validate, the number input and request that the
user reenter it if it is not in the proper range. The next two examples use
loops to accomplish this task.
EXAMPLE 10 This pseudocode validates the number entered using a post-test loop.
Repeat
Write "Enter a positive number ---> "
Input Num
Until Num > 0
In this technique for validating data, the prompt
Enter a positive number --->
is repeated until the number entered (Num) is positive.
ISBN: 0-536-12326-8
4.3 Applications of Repetition Structures 4 107
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
EXAMPLE 11 Sometimes, in validating data, we want to emphasize the fact that the user
has made an error by displaying a message to this effect. We can do this with
a pre-test loop, as illustrated in the following pseudocode.
Write "Enter a positive number ---> "
Input Num
While Num <= 0
4 Write "The number entered must be positive"
Write "Please try again ---> "
Input Num
End While
Notice that in validating input data with a pre-test loop, we use two Input
statements (and accompanying prompts). The first is positioned before
the loop and is always executed; the second is contained within the loop
and is executed only if the data entered is not in the proper range. Although
this means of validating input data is a little more complicated than that
used in Example 10, it is also more flexible and user-friendly. Within the
body of the data validation loop, you can provide whatever message best
suits the situation.
Validating integer Sometimes it is important that the number entered by the user be an
input integer--a whole number. (For a specific example of such a situation,
see Section 4.5.) How such input is validated depends on the program-
ming language. In this book, we will introduce the Int function to do the
job. (A function is a procedure that computes a specified value.)
The Int function An expression of the form, Int(X), where X represents a number,
numeric variable, or arithmetic expression, is the integer obtained by dis-
carding the fractional part, if any, of the value of X. For example, sup-
pose that Num1 = 15.25 and Num2 = 4.5. Then:
Int(Num1) = 15, Int(Num2) = 4, and Int(Num1 5.25) = 10
The Int function may appear anywhere in a program that an integer con-
stant is valid. For example, if Num is a numeric variable, then each of
the following statements is valid:
Write Int(Num)
Set Y = 2 * Int(Num 1) + 5
However, the statement Input Int(Num) is not valid.
The next example demonstrates how we use the Int function to vali-
date integer input.
EXAMPLE 12 This program segment checks that the number N entered by the user is an
integer, then displays a table of the squares of all integers from 1 to N.
ISBN: 0-536-12326-8
108 3 CHAPTER 4 Repetition Structures: Looping
Extended Prelude to Programming: Concepts and Design, Second Edition by Stewart Venit. Copyright © 2004 by Scott/Jones, Inc. Published by Scott/Jones, Inc., in conjunc-
tion with Addison Wesley, a division of Pearson Education.
Repeat
Write "Enter an integer:"
Input N
Until Int(N) = N
For Count = 1 Step 1 To N
Write Count, Count ^ 2
End For
If the number entered by the user in the Repeat ... Until loop is not an
integer, then the test condition, Int(N) = N , will be false and the loop will 4
be reentered. If the number entered is an integer, the test condition will
be true and the loop will be exited. Notice that the For loop will be exe-
cuted only if N is greater than or equal to 1. In that case, the table of
squares will be displayed; otherwise, the For loop will be skipped.
Validate Input Data Your programs should, whenever possible, validate input
STYLE POINTER data; that is, check that it is in the proper range. A pre-test or post-test loop
can be used for this purpose, as shown in Examples 10, 11, and 12.
Data validation is an example of defensive programming, writing
