csi 1301 algorithms - part 3 repetition/loop control structure

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

Upload: ibrahim-broadie

Post on 31-Mar-2015

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

CSI 1301

ALGORITHMS - PART 3REPETITION/LOOP

CONTROL STRUCTURE

Page 2: 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…..

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

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 N1Get N2…Get N100

Let Total = N1 + N2 + N3 + … + N99 + N100

Give Total What would we do for 1,000,000 numbers?

Page 4: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 5: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 6: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 7: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Loop Block

Set Up Set Up

TEST

TEST

Loop Block----------------Instruction 1Instruction 2

Loop Block----------------Instruction 1Instruction 2

ChangeChange

Page 8: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Setting up a Loop in an Algorithm (1)

Syntax

Set Up

Loop When (Test)Instruction 1

Instruction 2

……….

Change

Finish Loop

SemanticAfter 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.

Page 9: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Syntax

Set Up

LoopInstruction 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.

Setting up a Loop in an Algorithm (2)

Page 10: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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 GetsLoop

Get X

Finish LoopOr multiple Gives

LoopGive Answer

Finish Loop

Page 11: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 12: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.1 (a)

Name: SUM100Givens: N

Change: NoneResults: TotalIntermediates: CountDefinition: Total := SUM100(N)

MethodLet Total = 0Let Count = 0

Loop When (Count < 100)Get N

Let Total = Total + N

Let Count = Count + 1Finish Loop

Give Total

Write an algorithm to find the sum of 100 numbers. Place the test at the beginning of the loop.

Page 13: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.1 (b)

Name: SUM100Givens: N

Change: NoneResults: TotalIntermediates: CountDefinition: Total := SUM100(N)

MethodLet Total = 0Let Count = 0

LoopGet N

Let Total = Total + N

Let Count = Count + 1Finish Loop When (Count = 100)

Give Total

Write an algorithm to find the sum of 100 numbers. Place the test at the end of the loop.

Page 14: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.2

Setup– Let Sum = 0

– Let Value = 1

Test– Value <= N

Change– Let Value = Value + 1

Write an algorithm to calculate the sum from 1 to N. ie. (1+2+3+4+…N)

Page 15: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.2

Name: SUMN

Givens: N

Change: None

Results: Sum

Intermediates: Value

Definition: Sum := SUMN(N)

MethodGet N

Let Value = 1Let Sum = 0

Loop When (Value <= N)Let Sum = Sum + ValueLet Value = Value + 1

Finish Loop

Give Sum

Write an algorithm to calculate the sum from 1 to N. ie. (1+2+3+4+…N)

Page 16: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Trace 3.1

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

LN N Value Sum Test 1 4 2 1 3 0 4 (1<=4) 5 1 6 2 4 (2<=4) 5 3 6 3

4 (3<=4) 5 6 6 4

4 (4<=4) 5 10 6 5

4 (5<=4)

8 Output 10

Page 17: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 18: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 19: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 20: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 21: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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)

MethodLet Count = 0Let Sum = 0Let Again = True

Loop When (Count < 10) AND (Again)

Get N

Let Sum = Sum + NLet Count = Count + 1

Get AgainFinish Loop

Let AVG = Sum/Count

Give AVG

Page 22: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

LN N Count Sum Again AVG Test 1 0 2 0 3 Yes

4 (0<10)AND YES 5 1 6 1 7 1 8 Yes 4 (1<10)AND YES 5 3 6 4 7 2 8 Yes

4 (2<10)AND YES 5 5 6 9 7 3 8 Yes

4 (3<10)AND YES 5 3 6 12 7 4 8 No

4 (4<10) AND NO

10 311 Output 3

Page 23: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Base Algorithm 1

Write an algorithm to perform a COUNT.

Let COUNT = 0

Loop

……….Let COUNT = COUNT + 1

Finish Loop

Give COUNT

Page 24: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Base Algorithm 2

Write an algorithm to perform a SUM.

Let SUM = 0

LoopGet N……….Let SUM = SUM + N

Finish Loop

Give SUM

Page 25: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Base Algorithm 3

Write an algorithm to perform an AVERAGE.

Let SUM = 0Let COUNT = 0Loop

Get N……….Let SUM = SUM + NLet COUNT = COUNT + 1

Finish LoopLet Average = SUM/COUNTGive Average

Page 26: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 27: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Base Algorithm 6

Write an algorithm to perform a SEARCH.

Get SearchLet FOUND = FalseLOOP Until (FOUND Or No_More_Values)

Get ValueIf (Value = Search)

Let FOUND = TrueFinish LoopIf FOUND

Give ValueElse

Give “Not Found”

Page 28: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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 + NLet Count = Count + 1

Get Again Finish Loop When Not(Again)

Let Avg = Sum/Count

Give Avg

Page 29: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Trace 3.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

LN Sum Count N Avg Again Test1,2 0 0

4 1 5 (1>0) 6 1 7 1 8 Yes 9 Not(Yes)

4 -5 5 (-5>0) 8 Yes 9 Not(Yes)

4 5 5 (5>0) 6 6 7 2 8 Yes 9 Not(Yes)

4 3 5 (3>0) 6 9 7 3 8 No 9 Not(No)

10 311 Output 3

Page 30: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.5

Write an algorithm to find the largest of 5 numbers (range 1 - 10).

– 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

Page 31: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

LN Max Count LC N Test1,2,3 -1 1 5

4 (1<=5) 5 1 6 (1>-1) 7 1 8 2

4 (2<=5) 5 5 6 (5>1) 7 5 8 3 4 (3<=5) 5 8 6 (8>5) 7 8 8 4

4 (4<=5)5 36 (3>8)8 5 4 (5<=5)5 26 (2>8)8 6

4 (6<=5)

10 Output 8

Page 32: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Additional Materials

Page 33: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Flow Charts

Page 34: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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

Page 35: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.1(a)Name: SUM100

Givens: N

Change: None

Results: Total

Intermediates: Count

Definition: Total := SUM100(N)

StartSUM100

Let Total = 0Let Count = 0

(Count < 100)

Get N

Let Total = Total + NLet Count = Count + 1

Give Total

FinishSUM100

Y

N

Page 36: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.1(b)Name: SUM100

Givens: N

Change: None

Results: Total

Intermediates: Count

Definition: Total := SUM100(N)

StartSUM100

Let Total = 0Let Count = 0

(Count = 100)

Get N

Let Total = Total + NLet Count = Count + 1

Give Total

FinishSUM100

Y

N

Page 37: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.2

Name: SUMN

Givens: N

Change: None

Results: Sum

Intermediates: Value

Definition: Sum := SUMN(N)

StartSUMN

Get N

Let Value =1Let Sum =0

Value <= N

Let Sum = Sum + ValueLet Value = Value + 1

Give Sum

FinishSUMN

N

Y

Page 38: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.3

Name: AVERAGE10

Givens: N

Change: None

Results: AVG

Intermediates: Count, Sum

Again

Definition:

AVG = AVERAGE10(N)

StartAVERAGE10

Let Count = 0Let Sum = 0

Let Again = True

(Count < 10)AND

(Again)

Get N

Let Sum = Sum + NLet Count = Count + 1

Get Again

Let AVG = Sum/Count

Give AVG

FinishAVERAGE10

N

Y

Page 39: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.4

Name: AVGPOS

Givens: N

Change: None

Results: Avg

Intermediates:

Again, Sum, Count

Definition:

Avg := AVGPOS(N)

StartAVGPOS

Let Sum = 0Let Count = 0

Get N

If (N>0)

Let Sum = Sum + NLet Count = Count + 1

Get Again

(Again)

Let Avg = Sum/Count

Give Avg

FinishAVGPOS

N

Y

N

Y

Page 40: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.5

Name: MAX5

Givens: N

Change: None

Results: Max

Intermediates:

Count

LastCount (Constant)

Definition:

Max := Max5(N)

StartMAX5

Set LastCount = 5

Let Max = -1Let Count = 1

(Count <= LastCount)

Get N

If (N > Max)

Let Max = N

Let Count = Count + 1

Give Max

FinishMAX5

Page 41: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

NSD

Page 42: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

NSD

Create an L or Γ The test, while or until, goes in the row partThe 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

Page 43: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.1(a)Name: SUM100

Givens: N

Change: None

Results: Total

Intermediates: Count

Definition: Total := SUM100(N)

When (Count < 100)Get NLet Total = Total + NLet Count = Count + 1

Let Total = 0Let Count = 0

Give Total

Page 44: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.1(b)Name: SUM100

Givens: N

Change: None

Results: Total

Intermediates: Count

Definition: Total := SUM100(N)

Get NLet Total = Total + NLet Count = Count + 1Until (Count = 100)

Give Total

Let Total = 0Let Count = 0

Page 45: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.2

Name: SUMN

Givens: N

Change: None

Results: Sum

Intermediates: Value

Definition: Sum := SUMN(N)

While (Value <= N)Let Sum = Sum + ValueLet Value = Value + 1

Get NLet Value = 1Let Sum = 0

Give Sum

Page 46: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.3

Name: AVERAGE10

Givens: N

Change: None

Results: AVG

Intermediates: Count, Sum

Again

Definition:

AVG = AVERAGE10(N)

When (Count < 10) AND (Again)Get NLet Sum = Sum + NLet Count = Count + 1Get Again

Let Count = 0

Give AVGLet AVG = Sum/Count

Let Again = TrueLet Sum = 0

Page 47: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.4

Name: AVGPOS

Givens: N

Change: None

Results: Avg

Intermediates:

Again, Sum, Count

Definition:

Avg := AVGPOS(N)

Y NLet Sum = Sum + NLet Count = Count + 1

Do Nothing

Give AvgLet Avg = Sum/Count

Let Sum = 0Let Count = 0

Get NIf(N > 0)

Get AgainUntil Not(Again)

Page 48: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Algorithm 3.5

Name: MAX5

Givens: N

Change: None

Results: Max

Intermediates:

Count

LastCount (Constant)

Definition:

Max := Max5(N)

Y NLet Max = N Do Nothing

Let Max = -1Set LastCount = 5

While(Count <= LastCount)

Give MaxLet Count = Count + 1

If (N > Max)Get N

Let Count = 1

Page 49: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Homework

Page 50: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

In your homework (Lecture 9), you developed algorithms, and traces

reversing the digits in a three digit number and adding that number to 500determining the eldest of 2 peoplecalculating a sales commission

For each of these questions, revise the algorithm to:

Run the reversing algorithm multiple times until the user enters the value 999Run 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

Page 51: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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.

Page 52: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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.

Page 53: CSI 1301 ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

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.