CSC121 - Topic 5 (CONTROL STRUCTURE (REPETITION)
CSC121 - Topic 5 (CONTROL STRUCTURE (REPETITION)
CSC121:
INTRODUCTION
TO ALGORITHM
DESIGN AND
DEVELOPMENT
2
REPETITION/ITERATION IN
DAILY LIFE
3
ANALYSIS OF
PROBLEMS
REQUIRING
REPETITION
CONTROL
4
STRUCTURE
WHAT IS
REPETITION/ITERATION?
Iteration is basically the repetition of one or more steps in an algorithm
Executes the same section of program code over and over again, as long as a loop
condition of some sort is met with each iteration
Also called looping and the condition is accordingly called the loop condition/loop
control variable
5
SCENARIOS REQUIRING
REPETITION
Loops are used in many applications such as:
Program to
Program that
Application to calculate fees which
Program to outputs every
ensure that user data increase by 4
accumulate multiple number from 1
entries are valid by percent each year.
calculation in through 20 along
repeatedly Display the fees
business reports with its value
prompting the user. each year for the
doubled and tripled
next 10 years.
6
Can you think of
any other situations
where looping can
be applied?
7
WHY REPETITION/ITERATION IS
IMPORTANT
To perform Programmer can write
complicated tasks --> one set of instructions
is the ability to repeat that operates on
them multiple, separate sets of
data
Can structure
programming Repetition allows the
statements to be programmer to
repeated as long as efficiently use
specific conditions are variables
met
8
TYPE OF REPETITION
STRUCTURES
Loop
statements
while
Pre-test
Loop
for
Repetition
Structure
do…while
Post-test
Loop
do…until
9
PRE-TEST LOOPS
❑In each iteration, the loop control variable is tested first.
❑If it is true, the loop action(s) is executed; if it is false, the loop is terminated.
❑Types of pretest loop: while | for
Loop control
variable /
condition Control True
variable Action(s)
initialized at Loop control variable is
beginning of tested to determine
pretest loop False number of times
instructions within loop
body are processed
10
POST-TEST LOOPS
❑In each iteration, the loop action(s) is executed first.
❑Next, the loop control expression is tested.
❑If it is true, a new iteration is started; otherwise, the loop terminates.
❑Types of pretest loop: do…while | do…until
Actions/instructions
Action(s) are processed at least
once, the first time!
Control True
variable
Loop condition
appears at end
False
of posttest loop
11
SETTING THREE
REQUIREMENTS OF
A REPETITION
STRUCTURE:
INITIALIZATION,
CONDITION AND
UPDATING
1
2
USING A LOOP CONTROL
VARIABLE
❑ You can use a loop to execute a body of statements continuously as
long as some condition continues to be true.
❑ To ensure the loop runs correctly, the number of repetition/iteration
should end correctly
❑ You can declare a loop control variable to manage the number of
repetitions a loop performs. Three separate actions should occur
using a loop control variable:
1. A variable, the loop control variable is initialized (before entering the
loop)
2. The loop control variable is tested, and if the result is true, the loop body
is entered.
3. The body of the loop must take some action that alters the value of the
loop control variable (so that the while expression eventually evaluates
13 as false)
INITIALIZATION AND UPDATING
LOOP INITIALIZATION
Before a loop can start, some preparation is usually required. Such preparation is
called loop initialization. Initialization must be done before the first execution
of the body. It sets the stage for the loop actions.
LOOP UPDATE
How can the condition that controls the loop be true for a while and then change
to false…?
The answer is that something must happen inside the body of the loop to change
the condition. Otherwise, we would have an infinite loop. This changes the
resulting condition from true to false (are known as loop update). Updating is
done in each iteration, usually as the last action. If the body of the loop is
repeated m times, then the updating is also done m times.
14
INITIALIZATION AND UPDATING
Initialization
Initialization
Action(s)
Action(s) Updating
Updating
Pretest loop
Posttest
loop
15
WHILE LOOP
❑The general form of the while statement is:
while (expression)
statement;
❑The expression acts as a decision maker and is usually a logical expression. It provides an
entry condition. If it initially to true, the statement executes. The loop condition (the
expression) is then reevaluated.
❑The statement continues to execute until the expression is no longer true (false). Include an
exit condition that will eventually evaluate expression to be false.
❑A loop that continues to execute endlessly is called an infinite loop.
Exp Statement
True
False
16
CONTROLLING WHILE LOOP
REPETITION
When you write a loop, you must control the number of repetition it
performs. If you don’t, you run the risk of creating an infinite loop.
17
CONTROLLING WHILE LOOP
REPETITION
Counter-controlled Sentinel-controlled
2. Determine the highest mark in a class. The process stops when the user enters an invalid
mark.
3. Ask the user to enter 30 numbers. Count how many odd numbers.
4. Calculate the total salary of all staff in finance department. The number of staff will be
entered by the user.
5. Count how may odd numbers in a group of numbers. The process will end if user insert
press equal sign.
6. Calculate the total salary of all staff in finance department. The process ends when user
20 insert N (No) for stop the process.
ALGORITHM
DEVELOPMENT
FOR REPETITION
CONTROL
STRUCTURE
(PSEUDOCODE
2
AND FLOWCHART)
1
WHILE LOOP WITH A COUNTER
Start
Pseudo-code:
Start
num count = 0
num count = 0
while count < 4
print “Hello”
count = count +
count < 4? print
“Hello” 1
Yes
endwhile
No End
End count = count + 1
Start
initialize sum=0
initialize count=0
while count < 10
Display “Enter number:”
Read num
sum = sum + num
count = count + 1
endwhile
Display “Sum = “,sum
End
23
Scenario: Calculate sum of 10 integer
WHILE LOOP WITH A SENTINEL
VALUE
Start
Pseudo-code:
get response
Start
get response
response = Yes while response == ‘Y’
print
‘Y’? bankBal print bankBal
bankBal = bankBal + bankBal
No
bankBal = bankBal + bankBal *
*intRate
print “Have intRate Print “Do you want to see next year’s
a nice day” balance? Y or N…”
print “Do you want to see get response
next year’s balance Y or
N…” Endwhile
End
End
get
response
24
Scenario: Bank application
EXERCISE 5.1
2. Determine the highest mark in a class. The process stops when the user enters an invalid
mark.
3. Ask the user to enter 30 numbers. Count how many odd numbers.
4. Calculate the total salary of all staff in finance department. The number of staff will be
entered by the user.
5. Count how may odd numbers in a group of numbers. The process will end if user insert
press equal sign.
6. Calculate the total salary of all staff in finance department. The process ends when user
insert N (No) for stop the process.
25
EXERCISE 5.2
Design the pseudocode and flowchart for the questions in Exercise 5.1
26
NESTED LOOP
Introductory To Nested Loop
• Program logic gets more complicated when you must use loop within loops,
or nested loop.
• When one loop appears inside another, the loop that contains the other loop is
called the outer loop, and the loop that is contained is called the inner loop.
• You need to create nested loops when the values of two (or more) variables
repeat to produce every combination of values.
For example:
Suppose you want to write a program that produces a quiz answer sheet
like the one shown in Figure 11. The quiz has five parts with three
questions in each part, and you want a fill-in-the-blank line for each
question. You could write a program that uses 21 separate print
statements to produce the sheet, but it is more efficient to use nested loop.
Example: Nested loop
Part 1 START
1. ________ int PARTS = 5
2. ________
3. ________ int QUESTIONS = 3
Part 2
string PART_LABEL = “Part “
4. ________ string LINE = “. _____”
5. ________
6. ________ partCounter = 1
while partCounter <= PARTS
Part 3
7. ________ print PART_LABEL, partCounter
8. ________
9. ________ questionCounter = 1
while questionCounter < = QUESTIONS
Part 4
10. ________ print questionCounter, LINE
11. ________
12. ________
questionCounter = questionCounter + 1
endwhile
Part 5
13. ________ partCounter = partCounter + 1
14. ________ endwhile
15. ________
END
Figure 11: A quiz sheet answer Figure 12: Pseudocode for AnswerSheet program
Exercise: Nested loop
The number of times a loop executes can depend on a constant or a value
that varies.
Suppose you own a factory and have decided to place a label on every product
you manufacture. The label contains the words “Made for you personally by”
followed by the first name of one of your employees. Assume that for one week’s
production, you need 100 personalized labels for each employee.
(Note: the user is prompted for an employee’s name, while the user does not type
the QUIT value (“ZZZ”), the program continues).
32