Presentation on theme: "ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE"— Presentation transcript:
1ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE CSI 1301ALGORITHMS - PART 3REPETITION/LOOPCONTROL STRUCTURE
2Need for RepetitionAn algorithm with get/give, assignment and conditional branch instructions processes one set of data (givens) each time it is executedWhat 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 employeesWe could execute the algorithm multiple times or once, as in the following example…..
3Algorithm 3.1 Write an algorithm to find the sum of 100 numbers. Name: SUM100Givens:N1, N2, N3, … N99, N100Change:NoneResults: TotalIntermediates: NoneDefinition: Total := SUM100(N1, N2, N3… N100)MethodGet N1Get N2…Get N100Let Total = N1 + N2 + N3 + … + N99 + N100Give TotalWhat would we do for 1,000,000 numbers?
4Loop Block Clearly, we need a better way We need an instruction that Executes a block of instructions multiple times, andAfter each execution, tests to see if the block of instructions should be executed againThis instruction is called a loop (repetition) control instruction
5Parts of a Loop There are four parts to a loop Setup The conditions to be set before we enter the loopTest (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 BlockThe instructions that are to be executed repeatedlyChangeA change to one of the variables in the test so that we can exit the loop
6Two Styles of LoopsUsually we place the test before the instructions that are to be executedHowever, 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
7Loop Block Set Up Set Up TEST Loop Block ---------------- Instruction 1Instruction 2Loop BlockInstruction 1Instruction 2ChangeChangeTEST
8Setting up a Loop in an Algorithm (1) SyntaxSet UpLoop When (Test)Instruction 1Instruction 2……….ChangeFinish LoopSemanticAfter 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.
9Setting up a Loop in an Algorithm (2) SyntaxSet UpLoopInstruction 1Instruction 2……….ChangeFinish Loop When (Test)SemanticAfter 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.
10Loop InstructionsSince a loop works on a block of instructions, any set of instructions can be repeated, not just assignment and conditional branch instructionsFor example, multiple GetsLoopGet XFinish LoopOr multiple GivesGive Answer
11Algorithm 3.1 (a)Write an algorithm to find the sum of 100 numbers. Place the test at the beginning of the loop.Loop Set UpLet Total = 0Let Count = 0Loop TestContinue until 100 numbers have been read (Count <100)ChangeLet Count = Count + 1InstructionsGet NLet Total = Total + N
12Algorithm 3.1 (a)Write an algorithm to find the sum of 100 numbers. Place the test at the beginning of the loop.MethodLet Total = 0Let Count = 0Loop When (Count < 100)Get NLet Total = Total + NLet Count = Count + 1Finish LoopGive TotalName: SUM100Givens: NChange: NoneResults: TotalIntermediates: CountDefinition: Total := SUM100(N)
13Algorithm 3.1 (b)Write an algorithm to find the sum of 100 numbers. Place the test at the end of the loop.MethodLet Total = 0Let Count = 0LoopGet NLet Total = Total + NLet Count = Count + 1Finish Loop When (Count = 100)Give TotalName: SUM100Givens: NChange: NoneResults: TotalIntermediates: CountDefinition: Total := SUM100(N)
14Algorithm 3.2Write an algorithm to calculate the sum from 1 to N. ie. ( …N)SetupLet Sum = 0Let Value = 1TestValue <= NChangeLet Value = Value + 1
15Algorithm 3.2Write an algorithm to calculate the sum from 1 to N. ie. ( …N)Name: SUMNGivens: NChange: NoneResults: SumIntermediates: ValueDefinition: Sum := SUMN(N)MethodGet NLet Value = 1Let Sum = 0Loop When (Value <= N)Let Sum = Sum + ValueLet Value = Value + 1Finish LoopGive Sum
16Trace 3.1 Trace algorithm 3.2 when N is 4 (1) Get N (2) Let Value = 1 LN N Value Sum Test1 4(1<=4)(2<=4)(3<=4)(4<=4)(5<=4)8 Output 10Trace 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
17Complex TestsSometimes, 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 operatorsANDORNOTXOR
18Boolean Operators AND will return a TRUE only when both are TRUE X | Y | X AND YF | F | FF | T | FT | F | FT | T | TOR will return a TRUE when either is TRUEX | Y | X OR YF | F | FF | T | TT | F | TT | T | T
19Boolean OperatorsNOT will change a TRUE to a FALSE or a FALSE to a TRUEX | NOT(X)F | TT | FXOR will return a TRUE when either is TRUE, but NOT BOTHX | Y | X XOR YF | F | FF | T | TT | F | TT | T | F
20Algorithm 3.3Write 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 occurs10 numbers have been enteredThe user decides to stop entering numbersSetupLet Count = 0, Let Total = 0, Let Again = TrueTestAgain = True AND Count <= 10ChangeLet Count = Count + 1, Get Again
21Algorithm 3.3Write an algorithm to find the average of up to 10 numbers entered by the user.Name: AVERAGE10Givens: NChange: NoneResults: AVGIntermediates: Count, SumAgainDefinition:AVG = AVERAGE10(N)MethodLet Count = 0Let Sum = 0Let Again = TrueLoop When (Count < 10) AND(Again)Get NLet Sum = Sum + NLet Count = Count + 1Get AgainFinish LoopLet AVG = Sum/CountGive AVG
22LN N Count Sum Again AVG Test Yes(0<10)AND YES5 1Yes(1<10)AND YES5 3(2<10)AND YES5 5(3<10)AND YESNo(4<10) AND NO11 Output 3Trace 3.2Trace 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
23Base Algorithm 1 Write an algorithm to perform a COUNT. Let COUNT = 0 Loop……….Let COUNT = COUNT + 1Finish LoopGive COUNT
24Base Algorithm 2 Write an algorithm to perform a SUM. Let SUM = 0 Loop Get N……….Let SUM = SUM + NFinish LoopGive SUM
25Base Algorithm 3 Write an algorithm to perform an AVERAGE. Let SUM = 0 Let COUNT = 0LoopGet N……….Let SUM = SUM + NLet COUNT = COUNT + 1Finish LoopLet Average = SUM/COUNTGive Average
26Base Algorithms 4 and 5 Write algorithms to perform a MAX and MIN. Let MAX = - infinityLoopGet NIf (N > MAX)Let MAX = NFinish LoopGive MAXLet MIN = infinityLoopGet NIf (N < MIN)Let MIN = NFinish LoopGive MIN
27Base Algorithm 6 Write an algorithm to perform a SEARCH. Get Search Let FOUND = FalseLOOP Until (FOUND Or No_More_Values)Get ValueIf (Value = Search)Let FOUND = TrueFinish LoopIf FOUNDGive ValueElseGive “Not Found”
28Algorithm 3.4Write an algorithm to find the average of all positive numbers given by the user.Name: AVGPOSGivens: NChange: NoneResults: AvgIntermediates:Again, Sum, CountDefinition:Avg := AVGPOS(N)MethodLet Sum = 0Let Count = 0LoopGet NIf (N > 0)Let Sum = Sum + NLet Count = Count + 1Get AgainFinish Loop When Not(Again)Let Avg = Sum/CountGive Avg
29Trace 3.3LN Sum Count N Avg Again Test1,(1>0)6 1YesNot(Yes)(-5>0)(5>0)6 6(3>0)6 9NoNot(No)11 Output 3Trace 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
30Algorithm 3.5Write an algorithm to find the largest of 5 numbers (range ).Name: MAX5Givens: NChange: NoneResults: MaxIntermediates:CountLastCount (Constant)Definition:Max := Max5(N)MethodSet LastCount = 5Let Max = -1Let Count = 1Loop When (Count <= LastCount)Get NIf (N > Max)Let Max = NLet Count = Count + 1Finish LoopGive Max
31LN Max Count LC N Test1,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 8Trace 3.4Trace 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
34Flow 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 loopNote the Test can be at the bottom or the top as stated previously
35Algorithm 3.1(a) Name: SUM100 Givens: N Change: None Results: Total Intermediates: CountDefinition: Total := SUM100(N)
36Algorithm 3.1(b) Name: SUM100 Givens: N Change: None Results: Total Intermediates: CountDefinition: Total := SUM100(N)
37Algorithm 3.2 Name: SUMN Givens: N Change: None Results: Sum Intermediates: ValueDefinition: Sum := SUMN(N)
50In 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
51Develop 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.
52Write 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.
53Write 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.