# ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

## Presentation on theme: "ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE"— Presentation transcript:

ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE
CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Need for Repetition An algorithm with get/give, assignment and conditional branch instructions processes one set of data (givens) each time it is executed What would we do if we needed to process multiple sets of data? To calculate the grades for 150 students (instead of a grade for one student) To determine the payroll for all employees We could execute the algorithm multiple times or once, as in the following example…..

Algorithm 3.1 Write an algorithm to find the sum of 100 numbers.
Name: SUM100 Givens:N1, N2, N3, … N99, N100 Change:None Results: Total Intermediates: None Definition: Total := SUM100(N1, N2, N3… N100) Method Get N1 Get N2 Get N100 Let Total = N1 + N2 + N3 + … + N99 + N100 Give Total What would we do for 1,000,000 numbers?

Loop Block Clearly, we need a better way We need an instruction that
Executes a block of instructions multiple times, and After each execution, tests to see if the block of instructions should be executed again This instruction is called a loop (repetition) control instruction

Parts of a Loop There are four parts to a loop Setup
The conditions to be set before we enter the loop Test (included in the loop control instruction) The Boolean test to determine if the loop should be executed again (the same type of test used in a conditional branch instruction) Instruction Block The instructions that are to be executed repeatedly Change A change to one of the variables in the test so that we can exit the loop

Two Styles of Loops Usually we place the test before the instructions that are to be executed However, occasionally, we need to execute the instructions before we test; in this case, we place the test after the instructions that are to be executed repeatedly

Loop Block Set Up Set Up TEST Loop Block ----------------
Instruction 1 Instruction 2 Loop Block Instruction 1 Instruction 2 Change Change TEST

Setting up a Loop in an Algorithm (1)
Syntax Set Up Loop When (Test) Instruction 1 Instruction 2 ………. Change Finish Loop Semantic After the Set Up, the Test is evaluated, if its value is true, instruction1, instruction2,… are executed, and Test is evaluated again. Instruction1, Instruction2 are repeated as long as the Test is true. When the value of Test becomes false, the Loop ends and the instruction following the Loop is executed.

Setting up a Loop in an Algorithm (2)
Syntax Set Up Loop Instruction 1 Instruction 2 ………. Change Finish Loop When (Test) Semantic After the Set Up, instruction1, instruction2, … are executed and then Test is evaluated, if its value is true, instruction1, instruction2,… are executed and the Test is evaluated again. When the value of Test becomes false, the Loop ends and the instruction following the Loop is executed.

Loop Instructions Since a loop works on a block of instructions, any set of instructions can be repeated, not just assignment and conditional branch instructions For example, multiple Gets Loop Get X Finish Loop Or multiple Gives Give Answer

Algorithm 3.1 (a) Write an algorithm to find the sum of 100 numbers. Place the test at the beginning of the loop. Loop Set Up Let Total = 0 Let Count = 0 Loop Test Continue until 100 numbers have been read (Count <100) Change Let Count = Count + 1 Instructions Get N Let Total = Total + N

Algorithm 3.1 (a) Write an algorithm to find the sum of 100 numbers. Place the test at the beginning of the loop. Method Let Total = 0 Let Count = 0 Loop When (Count < 100) Get N Let Total = Total + N Let Count = Count + 1 Finish Loop Give Total Name: SUM100 Givens: N Change: None Results: Total Intermediates: Count Definition: Total := SUM100(N)

Algorithm 3.1 (b) Write an algorithm to find the sum of 100 numbers. Place the test at the end of the loop. Method Let Total = 0 Let Count = 0 Loop Get N Let Total = Total + N Let Count = Count + 1 Finish Loop When (Count = 100) Give Total Name: SUM100 Givens: N Change: None Results: Total Intermediates: Count Definition: Total := SUM100(N)

Algorithm 3.2 Write an algorithm to calculate the sum from 1 to N. ie. ( …N) Setup Let Sum = 0 Let Value = 1 Test Value <= N Change Let Value = Value + 1

Algorithm 3.2 Write an algorithm to calculate the sum from 1 to N. ie. ( …N) Name: SUMN Givens: N Change: None Results: Sum Intermediates: Value Definition: Sum := SUMN(N) Method Get N Let Value = 1 Let Sum = 0 Loop When (Value <= N) Let Sum = Sum + Value Let Value = Value + 1 Finish Loop Give Sum

Trace 3.1 Trace algorithm 3.2 when N is 4 (1) Get N (2) Let Value = 1
LN N Value Sum Test 1 4 (1<=4) (2<=4) (3<=4) (4<=4) (5<=4) 8 Output 10 Trace algorithm 3.2 when N is 4 (1) Get N (2) Let Value = 1 (3) Let Sum = 0 (4) Loop When (Value <= N) (5) Let Sum = Sum + Value (6) Let Value = Value + 1 (7) Finish Loop (8) Give Sum

Complex Tests Sometimes, a simple test is not adequate for either a conditional branch (If) or repetition (loop) control structure. For more complicated tests, we use the Boolean operators AND OR NOT XOR

Boolean Operators AND will return a TRUE only when both are TRUE
X | Y | X AND Y F | F | F F | T | F T | F | F T | T | T OR will return a TRUE when either is TRUE X | Y | X OR Y F | F | F F | T | T T | F | T T | T | T

Boolean Operators NOT will change a TRUE to a FALSE or a FALSE to a TRUE X | NOT(X) F | T T | F XOR will return a TRUE when either is TRUE, but NOT BOTH X | Y | X XOR Y F | F | F F | T | T T | F | T T | T | F

Algorithm 3.3 Write an algorithm to find the average of up to 10 numbers entered by the user. Execution of the algorithm stops whenever one of the following conditions occurs 10 numbers have been entered The user decides to stop entering numbers Setup Let Count = 0, Let Total = 0, Let Again = True Test Again = True AND Count <= 10 Change Let Count = Count + 1, Get Again

Algorithm 3.3 Write an algorithm to find the average of up to 10 numbers entered by the user. Name: AVERAGE10 Givens: N Change: None Results: AVG Intermediates: Count, Sum Again Definition: AVG = AVERAGE10(N) Method Let Count = 0 Let Sum = 0 Let Again = True Loop When (Count < 10) AND (Again) Get N Let Sum = Sum + N Let Count = Count + 1 Get Again Finish Loop Let AVG = Sum/Count Give AVG

LN N Count Sum Again AVG Test
Yes (0<10)AND YES 5 1 Yes (1<10)AND YES 5 3 (2<10)AND YES 5 5 (3<10)AND YES No (4<10) AND NO 11 Output 3 Trace 3.2 Trace algorithm 3.3 when the user enters only the numbers 1, 3, 5 and 3 (1) Let Count = 0 (2) Let Sum = 0 (3) Let Again = True (4) Loop When (Count < 10) AND (Again) (5) Get N (6) Let Sum = Sum + N (7) Let Count = Count + 1 (8) Get Again (9) Finish Loop (10) Let AVG = Sum/Count (11) Give AVG

Base Algorithm 1 Write an algorithm to perform a COUNT. Let COUNT = 0
Loop ………. Let COUNT = COUNT + 1 Finish Loop Give COUNT

Base Algorithm 2 Write an algorithm to perform a SUM. Let SUM = 0 Loop
Get N ………. Let SUM = SUM + N Finish Loop Give SUM

Base Algorithm 3 Write an algorithm to perform an AVERAGE. Let SUM = 0
Let COUNT = 0 Loop Get N ………. Let SUM = SUM + N Let COUNT = COUNT + 1 Finish Loop Let Average = SUM/COUNT Give Average

Base Algorithms 4 and 5 Write algorithms to perform a MAX and MIN.
Let MAX = - infinity Loop Get N If (N > MAX) Let MAX = N Finish Loop Give MAX Let MIN = infinity Loop Get N If (N < MIN) Let MIN = N Finish Loop Give MIN

Base Algorithm 6 Write an algorithm to perform a SEARCH. Get Search
Let FOUND = False LOOP Until (FOUND Or No_More_Values) Get Value If (Value = Search) Let FOUND = True Finish Loop If FOUND Give Value Else Give “Not Found”

Algorithm 3.4 Write an algorithm to find the average of all positive numbers given by the user. Name: AVGPOS Givens: N Change: None Results: Avg Intermediates: Again, Sum, Count Definition: Avg := AVGPOS(N) Method Let Sum = 0 Let Count = 0 Loop Get N If (N > 0) Let Sum = Sum + N Let Count = Count + 1 Get Again Finish Loop When Not(Again) Let Avg = Sum/Count Give Avg

Trace 3.3 LN Sum Count N Avg Again Test 1, (1>0) 6 1 Yes Not(Yes) (-5>0) (5>0) 6 6 (3>0) 6 9 No Not(No) 11 Output 3 Trace algorithm 3.4 when the user enters only the numbers 1, -5, 5 and 3 (1) Let Sum = 0 (2) Let Count = 0 (3) Loop (4) Get N (5) If (N > 0) (6) Let Sum = Sum + N (7) Let Count = Count + 1 (8) Get Again (9) Finish Loop When Not(Again) (10) Let Avg = Sum/Count (11) Give Avg

Algorithm 3.5 Write an algorithm to find the largest of 5 numbers (range ). Name: MAX5 Givens: N Change: None Results: Max Intermediates: Count LastCount (Constant) Definition: Max := Max5(N) Method Set LastCount = 5 Let Max = -1 Let Count = 1 Loop When (Count <= LastCount) Get N If (N > Max) Let Max = N Let Count = Count + 1 Finish Loop Give Max

LN Max Count LC N Test 1,2, (1<=5) (1>-1) (2<=5) (5>1) (3<=5) (8>5) (4<=5) (3>8) (5<=5) (2>8) (6<=5) 10 Output 8 Trace 3.4 Trace algorithm 3.5 when the user enters only the numbers 1,5,8,3 and 2 (1) Set LastCount = 5 (2) Let Max = -1 (3) Let Count = 1 (4) Loop When (Count <= 5) (5) Get N (6) If (N > Max) (7) Let Max = N (8) Let Count = Count + 1 (9) Finish Loop (10) Give Max

Flow Charts

Flow Charts The Diamond symbol is reused, to test the condition.
At the end of the block, the flow will reverse itself back to the top of the loop Note the Test can be at the bottom or the top as stated previously

Algorithm 3.1(a) Name: SUM100 Givens: N Change: None Results: Total
Intermediates: Count Definition: Total := SUM100(N)

Algorithm 3.1(b) Name: SUM100 Givens: N Change: None Results: Total
Intermediates: Count Definition: Total := SUM100(N)

Algorithm 3.2 Name: SUMN Givens: N Change: None Results: Sum
Intermediates: Value Definition: Sum := SUMN(N)

Algorithm 3.3 Name: AVERAGE10 Givens: N Change: None Results: AVG
Intermediates: Count, Sum Again Definition: AVG = AVERAGE10(N)

Algorithm 3.4 Name: AVGPOS Givens: N Change: None Results: Avg
Intermediates: Again, Sum, Count Definition: Avg := AVGPOS(N)

Algorithm 3.5 Name: MAX5 Givens: N Change: None Results: Max
Intermediates: Count LastCount (Constant) Definition: Max := Max5(N)

NSD

NSD Create an L or Γ The test, while or until, goes in the row part
The column controls what block is to be repeated NB this is done with two cells (1 row, 1 column) with no boarder between the two

Algorithm 3.1(a) Name: SUM100 Givens: N Change: None Results: Total
Intermediates: Count Definition: Total := SUM100(N)

Algorithm 3.1(b) Name: SUM100 Givens: N Change: None Results: Total
Intermediates: Count Definition: Total := SUM100(N)

Algorithm 3.2 Name: SUMN Givens: N Change: None Results: Sum
Intermediates: Value Definition: Sum := SUMN(N)

Algorithm 3.3 Name: AVERAGE10 Givens: N Change: None Results: AVG
Intermediates: Count, Sum Again Definition: AVG = AVERAGE10(N)

Algorithm 3.4 Name: AVGPOS Givens: N Change: None Results: Avg
Intermediates: Again, Sum, Count Definition: Avg := AVGPOS(N)

Algorithm 3.5 Name: MAX5 Givens: N Change: None Results: Max
Intermediates: Count LastCount (Constant) Definition: Max := Max5(N)

Homework

In your homework (Lecture 9), you developed algorithms, and traces
reversing the digits in a three digit number and adding that number to 500 determining the eldest of 2 people calculating a sales commission For each of these questions, revise the algorithm to: Run the reversing algorithm multiple times until the user enters the value 999 Run the eldest algorithm until the user indicates “no” to the question “Do you want to continue?” Run the sales commission algorithm for exactly 10 sales representatives

Develop an algorithm to assist a clerk in determining some statistics about students. For each student, she enters the name, gender (M or F), age and marital status (M or S). She wants to determine the number of married men, married women, single women and eligible bachelors (single men over 25). Each time she has completed entry of data for a student, the algorithm should give her a chance to indicate whether she has entered the data for all of the students.

Write an algorithm to determine the closing balance for a teller
Write an algorithm to determine the closing balance for a teller. The teller enters his opening balance and then a number of transactions. Deposits are entered as positive numbers and withdrawals are entered as negative numbers. He also needs to calculate the number of deposits and the number of withdrawals. The teller indicates that all transactions have been entered by entering a transaction with a value of 0.

Write an algorithm to calculate and display the total gross earnings, tax payable, medical deduction and net earnings for all employees. The user will input the hours worked and the hourly rate of pay for each employee. The gross earnings for each employee can be calculated from this information. The net earnings are calculated by subtracting the tax payable and medical deductions from the gross earnings. Tax payable is 20% of gross pay for the first \$300, 30% for the next \$200 and 40% thereafter. The medical deduction is calculated as 1% of gross pay. The user will indicate that all employee information has been entered by entering hours worked as 999.