Chapter 1 Control Structure Loop
Chapter 1 Control Structure Loop
Loop
(Part 1)
Knowledge:
Understand the various concepts of loop control structure
Skill:
Be able to develop a program involving loop control structure
Step a
false
condition
true
Step x
Step y
Step n
Testing Condition
First
Step a
condition
Step x
Step y
Step n
Testing condition
later
Step a
Step x
Step y
true
condition
false
Step n
Testing condition
later
Step a
Step x
Step y
true
condition
false
Step n
How Loops are Controlled
Condition Sentinel
Controlled Controlled
Counter Controlled
•1, 2, 3, 4, …
•…, 4, 3, 2, 1
Counter Controlled Loop
counter ← initialValue
false
test counter
value
true
Step x
Update counter
Step n
Counter Controlled Loop
counter
counter ←
= initialValue
initialValue
false
test counter
value
true
Step x
Update counter
Step n
Example:
Draw a flowchart for the Can you
following problem: identify the
Read 5 integer and display the input and
value of their summation. output???
Input : 5 integer
n1, n2, n3, n4, n5
Output: The summation of
n1, n2, .., n5
Input example: 2 3 4 5 6
Output example: 20
Assume input example: start
2 3 4 5 6
n1 2
Input n1
Input n2 n2 3
This flowchart does
not use loop, hence
we need to use 6 Input n3 n3 4
different variables
input n4 n4 5
input n5
n5 6
sum ← n1+n2+n3+n4+n5
sum 20
output sum
end
Counter-
Assume input
Controlled
example:
counter ← 1, sum ← 0 counter 1
2
3
4
5
6
2 3 4 5 6
Loop sum 14
20
0
2
5
9
false
counter < 6
n 2
3
4
5
6
true
input n
Uses only
3 variables
sum ← sum + n
This loop is
counter-controlled
counter++
The counter
output sum
Increases by 1
Decreasing Counter-Controlled Loop
counter ← 5, sum ← 0
false
counter > 0
true
input x
sum←sum+ x
counter--
output sum
Example: Draw a flowchart for this problem;
Given an exam marks as input, display the
appropriate message based on the rules below:
m 110
57
5
input m
“WRONG INPUT”
true
110
5
57<<0<0||0||5||57
>100
110
>100
>100 m<0 || m>100
false
>Condition-controlled
557 49
true
> 49 m>49
loop with its condition “PASS”
being tested at the end false
“FAIL”
WRONG INPUT
FAIL
PASS
input m
false
m<0 || m>100
true
“WRONG INPUT”
input m
Condition-controlled true
loop with its m>49 “PASS”
condition being false
tested first “FAIL”