ALGORITHMS - PART 3 REPETITION/LOOP CONTROL STRUCTURE

Slides:



Advertisements
Similar presentations
Decision Structures - If / Else If / Else. Decisions Often we need to make decisions based on information that we receive. Often we need to make decisions.
Advertisements

3-1 Chapter 3 Flow of Control (part a - branching)
CSI 1306 ALGORITHMS - PART 4 LIST PROCESSING. Lists Sometimes a problem deals with a list of values We represent such a list with a single name, and use.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 10P. 1Winter Quarter Repetition Structures.
CS 101 Introductory Programming - Lecture 7: Loops In C & Good Coding Practices Presenter: Ankur Chattopadhyay.
Do-while Loops Programming. COMP102 Prog Fundamentals I: do-while Loops /Slide 2 The do-while Statement l Syntax do action while (condition) l How it.
CSI 1306 PROGRAMMING IN VISUAL BASIC PART 2. Part 2  1. Strings  2. Translating Conditional Branch Instructions  3. Translation Set 2  4. Debugging.
ALGORITHMS - PART 2 CONDITIONAL BRANCH CONTROL STRUCTURE
CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
True or false A variable of type char can hold the value 301. ( F )
Branching Constructs Review l what are branching constructs? what type of branching constructs have we studied? l what is nested if? l what is multiway.
Computer Science 1620 Loops.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 3, Lecture 2.
Chapter 5: Control Structures II (Repetition)
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control Loops in Java.
Basic Building Blocks of Programming. Variables and Assignment Think of a variable as an empty container Assignment symbol (=) means putting a value into.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Copyright © Texas Education Agency, Computer Programming For Loops.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 6 Looping.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Repetition Control Structure. Introduction Many applications require certain operations to be carried out more than once. Such situations require repetition.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Topic: Control Statements. Recap of Sequence Control Structure Write a program that accepts the basic salary and allowance amount for an employee and.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 7: The Repetition Structure Introduction to Programming with C++ Fourth Edition.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Microsoft® Small Basic Conditions and Loops Estimated time to complete this lesson: 2 hours.
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
IST 210: PHP Logic IST 210: Organization of Data IST2101.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 10P. 1Winter Quarter Repetition Structures Lecture 10.
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
Chapter 4 Repetition Statements (loops)
Introduction To Repetition The for loop
ALGORITHMS CONDITIONAL BRANCH CONTROL STRUCTURE
Programming Logic and Design Fourth Edition, Comprehensive
REPETITION/LOOP CONTROL STRUCTURE
Branching Constructs Review
Topic 5 for Loops -Arthur Schopenhauer
CiS 260: App Dev I Chapter 4: Control Structures II.
JavaScript: Control Statements.
Conditinoal Constructs Review
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Outline Altering flow of control Boolean expressions
Conditinoal Constructs Review
Faculty of Computer Science & Information System
Chapter 6: Repetition Statements
Computer Science Core Concepts
CS2011 Introduction to Programming I Selections (I)
FLUENCY WITH INFORMATION TECNOLOGY
Repetition Statements (Loops) - 2
PROGRAM FLOWCHART Iteration Statements.
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement.
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. (1+2+3+4+…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. (1+2+3+4+…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 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 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 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 4 (2<10)AND YES 5 5 6 9 7 3 4 (3<10)AND YES 6 12 7 4 8 No 4 (4<10) AND NO 10 3 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,2 0 0 4 1 5 (1>0) 6 1 7 1 8 Yes 9 Not(Yes) 4 -5 5 (-5>0) 4 5 5 (5>0) 6 6 7 2 4 3 5 (3>0) 6 9 7 3 8 No 9 Not(No) 10 3 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 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

LN Max Count LC N Test 1,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 3 6 (3>8) 8 5 4 (5<=5) 5 2 6 (2>8) 8 6 4 (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

Additional Materials

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.