Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 25

CHAPTER 4 : REPETITION /LOOP / ITERATION CONTROL

STRUCTURE
LESSON OUTCOME

At the end of this chapter student should be able to :


- Apply types of iteration structure on the given problems
- Understand the execution of pseudocode uses loop control structure
- Apply iteration structure on the given problems
- Differentiate simple loop and nested loop
- Understand the execution of pseudocode uses nested loop control structure
- Apply nested loop/iteration structure on the given problems

Introduction
A simple problem may be solved using simple statements. The arrangement of statements in
an algorithm implements sequential control structure. Meanwhile to solve a problem that
involves decision making to choose an action implements selection control structure. In other
cases we want to solve a problem that needs to do the same process for several times. For this
type of problem it is suitable to use repetition or loop or iteration control structure

Example
Calculate an average of 5 numbers.

Problem definition:
information average
Data 5 numbers
Formula summing up all numbers and divide by 5

An expected screen:

Enter 5 numbers :

5 times

The average :
OR

1
Enter a number :

Enter a number :

5 times

Enter a number :

The average :

A detailed algorithm:

Start
Display “Enter 5 numbers : “
Read no1, no2, no3, no4, no5
sum  no1 + no2 + no3 + no4 + no5
average  sum / 5
Display “ The average = “ , average
End

Example :
Calculate the average of 10 numbers.

Problem definition:
information average
Data 10 numbers
Formula summing up all numbers and divide by 10

An expected screen:

Enter 10 numbers :

:: 10 times
::

The average :

2
A detailed algorithm:

Start
Read no1, no2, no3, no4, no5, no6, no7, no8, no9, no10
sum  no1 + no2 + no3 + no4 + no5 +no6 + no7 +no8 +no9 + no10
average  sum / 10
Display “ the average = “ , average
End

Example :
Calculate the average of 100 numbers.

Problem definition:
information average
Data 100 numbers
Formula summing up all numbers and divide by 100

An expected screen:

Enter 100 numbers :

:: 100 times
::

The average :

The above algorithm can also be written as follows :


Start
Display “Enter 5 numbers : “
Read no1
Read no2
Read no3
Read no4
Read no5
Initialize sum with 0
sum  sum + no1
sum  sum + no2
sum  sum + no3
sum  sum + no4
sum  sum + no5
average  sum / 5
Display “ The average = “ , average
End

3
The statements in the above algorithm can be rearrange as follows :
Start
Initialize sum with 0
Display “Enter 5 numbers : “

Read no1
sum  sum + no1

Read no2
sum  sum + no2

Read no3
sum  sum + no3

Read no4
sum  sum + no4

Read no5
sum  sum + no5

average  sum / 5
Display “ The average = “ , average
End

In the above algorithm, there are five statements that execute the same processes ( Read a
number and add the number to variable sum). We also can change the above algorithm as
follows :

Start
Initialize sum with 0
Display “Enter 5 numbers : “
Read num
sum  sum + num

Read num
sum  sum + num

Read num
sum  sum + num

Read num
sum  sum + num

Read num
sum  sum + num

average  sum / 5
Display “ The average = “ , average

4
End

Now we want to see how the above modified algorithm will be executed.

To simplify the algorithm in Example above, we use repetition control structure as follows:

start
initialize sum with 0
initialize count to 0
display “enter 5 numbers : “
while(count<5)
read num
sum  sum + num
count = count + 1
endwhile
average  sum / 5
display “ the average = “ , average
end

Solution for Example :


Start
Initialize sum with 0
Display “Enter 10 numbers : “
Initialize count to 0
while(count<10)
Read num
sum  sum + num
count = count + 1
endwhile
average  sum / 10
Display “ The average = “ , average
End

Note: The algorithm is simpler and shorter than the previous algorithms without the
repetition structure.

Solution for Example :

A detailed algorithm:
Start
Display “Enter rate per hour:”
Read rate
total-salary  0
count = 0
while(count< 5)
Display “Enter hours worked:”
Read hours-worked
Multiply rate with hours-worked and store the result in a variable salary
total-salary  total-salary + salary

5
count = count + 1
endWhile
Display “Total salary for 5 employees =” , total-salary
End

Note: Calculation for total-salary also has to be done in the loop because we only use one
variable (salary) to hold the salary of five employees.

Example :
Given 5 marks. Calculate the total of marks which are not less than 50.

The result of problem definition :


Information total marks which is greater than 50
Data 5 marks

A detailed algorithm :
Start
Read mark1, mark2, mark3, mark4, mark5
total  0
If (mark1 ≥ 50)
total  total + mark1
endIF
If (mark2 ≥ 50)
total  total + mark2
endIF
If (mark3 ≥ 50)
total  total + mark3
endIF
If (mark4 ≥ 50)
total  total + mark4
EndIF
If (mark5 ≥ 50)
total  total + mark5
EndIF
Display total
End

The above algorithm can be simpilify as follows :


Start
total  0
count = 0
while(count< 5)
Read mark
If (mark ≥ 50)
total  total + mark
EndIF
count = count + 1

6
endWhile
Display total
End

All Examples show how we can get a simpler and shorter solution using repetition control
structure.

The flowchart for while…endWhile statement to repeat the same processes for N times:

initialize counter with 1

NO
counter ≤ N

yes

Statement(s) to repeat

Increase counter by 1

EXIT FROM THE LOOP

The pseudocode for while…endWhile statement for sentinel loop

initial value of a loop


while ( condition to continue the loop )
statement(s) to be repeat
statement to make the loop stops
endWhile

7
The flowchart for repetition control structure:

initialize the loop

NO
condition to continue
the loop

yes

Statement(s) to repeat

Statement to make the loop stops

EXIT FROM THE LOOP

When using flowchart implementation for counter loop, the following three statements must
be available:

i. initialize counter with 1 or 00


ii. counter ≤ N or < N
iii. increase counter by 1
where N represent the number of repetition.

When using flowchart implementation for sentinel loop, the following three statements must
be available:
i. initialize the loop
ii. condition of the loop
iii. statement to make the condition is false.

8
Examples of problem that we know the number of repetition needed:
i. Ask the user to enter 30 numbers. Count how many odd numbers.
ii. Determine the highest mark in a class of 35 students.
iii. Find the average of N cgpa in the class DCS1.
iv. Calculate the total salary of all staff in finance department. The number of staff will be
entered by the user.

Examples of sentinel loop problem:


i. Count how may odd numbers in a group of numbers that ends with zero.
ii. Determine the highest mark in a class. The process stops when the user enters an
invalid mark.
iii. Calculate the total salary of all staff in finance department. The process ends when there
is no more data to process.
Example:
a. calculate the total
b. calculate the average
c. find maximum value and minimum value
d. count

The following algorithms are for the above purposes:

(a) Calculate the total for a group of numbers


Start
Initialize variable sum with 0
Display “Insert 1 to countinue the loop, 0therwise to stop”
Input continue
While(continue =1)
Read number
sum=sum + number

Display “Insert 1 to countinue the loop, 0therwise to stop”


Input continue
endWhile
Display sum
End
Start

sum = 0

counter = 1

no

counter ≤ 5

yes

9
number average = sum/5

sum = sum + number “ The average = “,

average

counter = counter + 1

End

(b) Calculate the average for a group of numbers


Start
Set sum with 0
Set count with 0
Display “Insert 1 to countinue the loop, 0therwise to stop”
Input continue
While(continue =1)
sum  sum + num
add 1 to count
Display “Insert 1 to countinue the loop, 0therwise to stop”
Input continue
endWhile
average  sum / count
Display average
End

(c) Find the maximum/highest/biggest and the minimum/lowest/smallest

There are three categories to solve this type of problem.

i) The limit values are known. An example is a problem involving student’s mark. We
know that the range of marks are 0.0 to 100.0. Another example of problem is to
manipulate CGPA values where the values of CGPA are in a range of 0 to 4.0.

ii) The lowest value is known but the highest value is unknown. An example is to process
salaries of staffs. Of course the lowest salary is RM0.00 but the highest salary is
unknown.

10
iii) The value of the lowest and the highest is unknown. An example is to find the biggest
or the smallest number for group of numbers. We do not know the range of values
involved.

i) The limit values are known.

Algorithm to find the highest mark :


Start
Max=-999
Display “Insert Y to continue”
Input answer
while(answer = ‘Y’)
Read data
If ( data > max )
max  data
EndIF
Display “Insert Y to continue”
Input answer
endWhile
Display max
End
Note: The range of mark are 00.0 to 100. The lowest value is 0.0. The above statement :
assign the lowest value to the variable max can be written as max  0.0 as follows:

Start
max  0.0
Display “Insert Y to continue”
Input answer
while(answer = ‘Y’)
Read data
If ( data > max )
max  data
EndIF
Display “Insert Y to continue”
Input answer
endWhile
Display max
End

Algorithm to find the lowest mark :


Start
min = 100
Display “Insert Y to continue”
Input answer
while(answer = ‘Y’)
Read data
If ( data < min )
min  data
EndIF

11
Display “Insert Y to continue”
Input answer
endWhile
Display min
End

Note : set the first data into variable min.


Start
Read data
min = data
Display “Insert Y to continue”
Input answer
while(answer = ‘Y’)
Read data
If ( data < min )
min  data
EndIF
Display “Insert Y to continue”
Input answer
endWhile
Display min
End
The following algorithm is used to count how many even numbers in a group of data.

Start
count-even  0
Read data
Display “Insert Y to continue”
Input answer
while(answer = ‘Y’)
If ( data %2 =0 )
Add 1 to count-even
EndIF
Read data
Display “Insert Y to continue”
Input answer
Display count-even
End

Algorithm to calculate the total salary:

Start
Display “Enter rate per hour:”
Read rate
total-salary  0
counter  1
while(counter<=5)
Display “Enter hours worked:”
Read hours-worked

12
Salary = rate X hours-worked
total-salary  total-salary + salary
counter=counter + 1
endWhile
Display “Total salary for 5 employees =” , total-salary
End

Start

”Enter rate per hour:”


rate

total-salary = 0

counter = 1

no
counter ≤ 5

yes

“Enter hours worked:” “Total salary for 5 employees


=”
hours-worked total-salary

salary = rate x hours-worked


total-salary = total salary + salary End
counter = counter + 1

13
14
Example
Trace the following algorithm. Determine the output.
Start
count = 0
Display “Enter a number : “
Read number
Set n to 2
Repeat (number – 2 ) times
If ( number is divisible by n )
count = count + 1
EndIF
Increase n by 1
endRepeat
If ( count == 0)
Display “ message1 “
Else
Display “ message2 “
End
Test with the following data :
i. 9 ii. 5 iii. 4
iv. 7 v. 11

EXERCISE :

Given the following pseudocode.


Start
Read numb
count  0
set I with 2
while (I < numb)
If ( numb % I =0)
count  count + 1
EndIF
Add 1 to I
endWhile
If ( count == 0 )
Display “ message1 “
Else
Display “ messsage2”
EndIF
End

a) Trace the above algorithm wih the following data :


i. 5
ii. 4
iii 9
iv 16

15
b) What is the purpose of the algorithm.
c) Replace message1 and message2 with suitable words.

2. Trace the following algorithm.


Start
N 15;
Set ppp with 2
While(ppp<15)
Display ppp
Add ppp by 2
endWhile
End

3. Trace the following algorithm.


Start
i= 0
While(i<5)
Read data
If ( data is odd OR data % 5 == 0 )
Display data , “ “
EndIF
i=i+1
endWhile
End

Test with the following data :


a. 1, 15, 6, 90, 66
b. 3, 66, 33, 21, 30
c. 3, 6, 9, 21, 81

4. Given the following algorithm. Trace it.


Start
Counter  0
x0
y 0
set p with 2
while(Counter <7)
Read no
If ( no is greater than 0 )
If ( no is divisible by 4 )
Add 1 to x
Else
Add no to y
EndIF
Counter=Counter + 1
endWhile
Display message “message1 “ , x
Display newline
Display message “message2 “ , y

16
End

a. Trace and what is the output.


i. -12, 15, 6, -9, 90, 66, -3
ii. -3, -6, -90, -66, -33, -21, -30
iii. 45, 23, 10, 5, 4, 6, 9
iv. 30, -30, -40, 40, 80, -80, 9

b. What is actually done by the above algorithm.


c. Replace message1 and message2 with suitable words.

Other example of Sentinel Loop


A sentinel loop is scenario where the exact number of repetition is unknown. But there
must be a condition to stop the repetition. The syntax is:

initial value of a loop


while ( condition to continue the loop )
statement(s) to be repeat
statement to make the loop stops
endWhile

All statements in between while .. end while will be executed when the condition is false.
The repetition is stop when the condition is true.

Examples of while …end while statement for sentinel loop:

a. Input and display a group of numbers that ends with 999.


Read number
while ( number is NOT 999 )
Display number
Read number
end while

a. Input mark of students. Display mark which is less than 50. Stop the process when
the user enters invalid mark.
Read mark
while ( mark > 0.0 AND mark ≤ 100 )
If ( mark < 50 )
Display mark
endIF
Read mark
end while

OR

17
Read mark
while ( ! (mark < 0.0 OR mark > 100) )
If ( mark < 50 )
Display mark
endIF
Read mark
end while

Calculate the mark and the grade for students. The mark is the average of two highest test
mark between three test marks. The process stops when there are no more data to process.
Use the following table to determine the grade.
Marks Grade
100 – 80 A
79 – 65 B
64 – 60 C
59 – 40 D
39 – 0 E

Problem definition :
information mark and grade
Data 3 test marks for each student ( until end of data )

The average of two highest tests between three tests is calculated as follows :
average = ( total of three tests – lowest mark ) / 2

A detailed algorithm :
Start
data  ‘y’
while ( data == ‘y’ )
Read test1, test2, test3
//find the lowest test
If ( test1 < test2 AND test1 < test3 )
min  test1
Else
If ( test2 < test3 )
min  test2
Else
min  test3
EndIF
EndIF
//calculate the average of 2 highest marks
mark  (test1 + test2 + test3 – min) / 2

//determine the grade


If ( mark ≥ 80 )
grade  ‘A’
Else
If ( mark ≥ 65 )
grade  ‘B’
18
Else
If ( mark ≥ 60 )
grade  ‘C’
Else
If ( mark ≥ 40 )
grade  ‘D’
Else
grade  ‘E’
EndIF
EndIF
EndIF
EndIF
Display mark, grade
Display “anymore data ?( y/n )”
Read data
//endWhile
End

Example:
Display the following menu.
choice Operation
+ add 2 numbers
* multiply 3 numbers
- difference of 2 numbers
x exit
Ask the user to enter a choice. Repeat until the user enters ‘x’ as a choice.

Problem definition:
Information Sum of 2 numbers OR product of 3 numbers OR
difference of 2 numbers
Data 2 numbes, OR 3 numbers

Detailed Algorithm:
Start
Display " choice Operation "
Display newline
Display " + add 2 numbers "
Display newline
Display " * multiply 3 numbers "
Display newline
Display " - dIfferent of 2 numbers “
Display newline
Display " x exit "
Display newline
Display "enter a choice : ";
Read choice

While ( choice != ‘x )
If ( choice == '+')
Display "enter 2 numbers "

19
Read no1 , no2
add  no1 + no2
Display "addition = " , add
Else
If ( choice == '*' )
Display "enter 3 numbers "
Read no1 , no2 , no3
multiply  no1 * no2 * no3
Display "Multiply = " , multiply
Else
If ( choice == '-' )
Display "enter 2 numbers "
Read no1 , no2 ;
If ( no1 > no2 )
dIff  no1 - no2
Else
dIff  no2 – no1
EndIF
Display "dIfferent = ", dIff
EndIF
edIf
EndIF
Display menu
Read choice
endWhile
End

Nested Loop
What it means by nested loop is inside a loop there is another loop. In this situation, we
have what we call as inner loop and outer loop. The execution of this type of structure is,
the computer will finish the inner loop for every iteration for outer loop.

Format for nested loop is as follows using repeat..endRepeat statetement

Repeat 5 times

::

Repeat 4 times outer loop


:::
:: inner loop
endRepeat //4 times iteration
endRepeat //4 times iteration

::

20
Flowchart for a nested loop as follows :

Initial value for outer loop

false condition for true


outer loop
::::

EXIT FROM NESTED LOOP Initial value for inner loop

Condition false
for inner loop
true

statement(s) in inner loop

statement to make inner loop stops

:::

statement to make outer loop stops

21
Execution of Nested Loop

Example :
Look at the following nested loop. We want to see how the following algorithm will be
executed.

Start
Set out-counter with 1 //1
Repeat 3 times //2
Display newline //2.1
Display “ outer loop = " , out-counter; //2.2
Display newline //2.3
Set inner-counter with 1 //2.4
Repeat 2 times //2.5
Display “ inside inner loop = " , inner-counter //2.5.1
Add 1 to inner-counter //2.5.2
EndRepeat

Increase out-counter by 1 //2.6


EndRepeat
End

The expected screen is:

outer loop = 1
inside inner loop = 1 inside inner loop = 2
outer loop = 2
inside inner loop = 1 inside inner loop = 2
outer loop = 3
inside inner loop = 1 inside inner loop = 2

Diagram 6.39 : Events in Computer Memory and Expected Screen for Example 6(x)

Example 6(y)
Given the following pseudocode. Trace and what is the output.

Start
j=0
While(j< 3)
i=0
While(i< 3)
Display “&”
i=i+1
endWhile
Display newline
j= j + 1
22
EndWhile
End
Execution of above pseudocode

Outer loop inner loop


1st repetition
Display ’&’
Display ’&’
Display ’&’
Display newline

2nd repetition
Display ’&’
Display ’&’
Display ’&’
Display newline

3rd repetition
Display ’&’
Display ’&’
Display ’&’
Display newline

An expected screen:

&&&
&&&
&&&

Example :
You are given 3 sets of data. Each set consists of 5 numbers. Find the biggest number for
each set.

Result of problem definition :


Information the biggest number ( 3 times )
Data 5 numbers ( 3 times )

We have to use an algorithm to find the maximum number between five numbers for each
set. This process has to be repeated for three times.

23
Algorithm to find a maximum between five numbers is :
Start
Read no1
max = no1
i=0
while(i<4)
Read number
If (number > max)
max = number
EndIF
i= i + 1
endWhile
Display max
End

Note : the number of repetition for the loop only 4 times because the first number is
entered before the loop.

The above process has to be repeated for three times as follows:

Start
j=0
While(j< 3)
Read no1
max = no1
i=0
while(i<4)
Read number
If (number > max)
max = number
EndIF
i= i + 1
endWhile
Display max
j= j + 1
endRepeat
End

24
EXERCISE
Write the algorithm for Display all the following diagrams.
1.
*******
******
*****
****
***
**
*

2.
*******
******
*****
****
***
**
*
3.
1
12
123
1234
12345

4.
& &
& &
& &
&&&&&&&&
& &
& &
& &

5.
EEEEEEE
E
E
EEEEEEE
E
E
EEEEEEE

25

You might also like