Objectives In this chapter, you will learn about:

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

Programming with Microsoft Visual Basic 2008 Fourth Edition
Programming with Microsoft Visual Basic th Edition
Programming Logic and Design Eighth Edition
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
Programming Logic and Design Sixth Edition
CS0004: Introduction to Programming Repetition – Do Loops.
Programming Logic and Design, Third Edition Comprehensive
Programming Logic and Design Seventh Edition
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Repeating Actions While and For Loops
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 5: Loops and Files.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
An Object-Oriented Approach to Programming Logic and Design Chapter 6 Looping.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 5: Control Structures II (Repetition)
Programming Logic and Design Fifth Edition, Comprehensive
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
6 Chapter 61 Looping Programming Logic and Design, Second Edition, Comprehensive 6.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 6 Looping.
Chapter 6: The Repetition Structure
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
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.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Chapter 7 Problem Solving with Loops
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter 7: The Repetition Structure Introduction to Programming with C++ Fourth Edition.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
REPETITION CONTROL STRUCTURE
Lecture 7: Repeating a Known Number of Times
Programming Logic and Design Fourth Edition, Comprehensive
Loop Structures.
CHAPTER 5A Loop Structure
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5: Repetition Structures
( Iteration / Repetition / Looping )
Learning About the Loop Structure (continued)
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
A First Book of ANSI C Fourth Edition
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
Chapter 8: More on the Repetition Structure
Programming Logic and Design Fifth Edition, Comprehensive
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Objectives In this chapter, you will learn about: Counter-controlled and sentinel controlled loops Nested loops Using a for loop Common loop applications Loop control structure in RAPTOR repeat until true rather than repeat while true

Understanding the Advantages of Looping control structure that repeats a set of actions (loop body) while some condition remains true or until some condition becomes true.

Loop Control Structure in RAPTOR In RAPTOR: you repeat the body of the loop UNTIL the condition evaluates to true. RAPTOR lets you structure your loop as one of three types: Pre-Test loop ( while / for ) Mid-Test loop illegal in our book Post-Test loop ( do … while ) Our book only shows us pre-test loops. RAPTOR Loop Symbol Note: In most languages (including Java) you repeat the loop body while the condition remains true

Figure 5-1 The loop structure (pre-test loop) Our book calls this a while loop

Looping Definite and Indefinite Loops Looping may be achieved using either a definite loop or an indefinite loop A definite loop is also referred to as a counter-controlled loop An indefinite loop is also referred to as a sentinel-controlled loop For a definite loop, the loop body will be executed a specific number of times. For an indefinite loop, the number of times the body of the loop should be executed can be different for each run of a program

Using a Counter-Controlled while loop As long as a boolean expression (the condition) remains true, the while loop’s body executes. RAPTOR keep executing UNTIL the condition becomes true Essential Steps: Create and initialize a loop control variable (lcv) Determine the upper or lower limit for the lcv Determine the step (increment or decrement) for the lcv Determine the boolean expression (condition) that will control the loop Each iteration of the loop, update the lcv

Using a Definite (Counter-Controlled) Loop Must the condition be true or false for the loop body to be executed? In RAPTOR, what would the condition be? How many times is “Hello” displayed? lcv is: count Figure 5-3 A counter-controlled while loop

Using an Indefinite Loop (Sentinel-Controlled) with a Sentinel Value May be performed a different number of times each time the program executes Essential steps: Identify a sentinel value (value outside the range of valid input data) that will be used as the loop exit condition name = QUIT //where QUIT is a named constant sentinel value End_of_input //RAPTOR sentinel module expression Java  hasNext( ) == false //Java method to evaluate end of input condition Each iteration of the loop get a new input value to compare to the sentinel value.

Must the condition be true or false for the loop body to be executed? In RAPTOR, what would the condition be? Figure 5-4 An indefinite while loop that displays “Hello” as long as the user wants to continue

Understanding the Loop in a Program’s Mainline Logic Three steps that should occur in every properly functioning loop Initialize the variable that will control the loop ( sentinel or counter value ) Test the condition to determine whether the loop body executes Update (aka alter) the loop control variable increment/decrement the lcv get a new input value to compare to the sentinel value

Nested Loops Nested loops: Outer loop: Inner loop: loop within another loop Outer loop: loop that contains the other loop Inner loop: loop that is contained Needed when values of two (or more) variables repeat to produce every combination of values

Figure 5-8 Flowchart and pseudocode for AnswerSheet program Must the condition be true or false for the loop body to be executed? In RAPTOR, what would the condition be? RAPTOR / Java <= versus > = versus != > versus <= “flip” the operator! Figure 5-8 Flowchart and pseudocode for AnswerSheet program

Common Loop Mistakes Neglecting to initialize the loop control variable Neglecting to update the loop control variable Loop executes one too many or one too few times operator: < or <= OR > or >= number of iterations = Last used – First used + 1 Including statements inside the loop that belong outside the loop

Figure 5-10 Incorrect logic for greeting program because the loop control variable initialization is missing

Programming Logic & Design, Sixth Edition Figure 5-10 Incorrect logic for greeting program because the loop control variable is not altered Programming Logic & Design, Sixth Edition

Programming Logic & Design, Sixth Edition For a sentinel-controlled loop the only operators you should use in the condition are = or != Figure 5-12 Incorrect logic for greeting program because the wrong test is used in the condition Programming Logic & Design, Sixth Edition

Avoiding Common Loop Mistakes (continued) including statements inside the loop that belong outside the loop Example: discount every item by 30 percent Inefficient because the same value is calculated 100 separate times for each price that is entered Move outside loop for efficiency

Figure 5-13 Inefficient way to produce 100 discount price stickers for differently priced items

Figure 5-14 Improved discount sticker-making program

Using a for Loop for statement or for loop is a definite loop specifically, it is a pre-test loop can be used in pseudocode or a Java program Remember, keywords like while, for, do have no meaning in a flowchart! Puts all of the loop control expressions in the for loop header Initialize Test Update Takes the form: [initial, final] for loopControlVariable = initialValue to finalValue [step stepValue] do something endfor

Using a for Loop (continued) Example pseudocode for loop for count = 0 to 3 step 1 [0,3] output “Hello” end for Initializes count to 0 Checks count against the limit value 3 (test) If evaluation is true, for statement body prints the label Executes 4 times ( last=3, first=0, 3-0+1 equals 4 ) Increases count by 1 (update) while loop: count = 0 while count <= 3 or while count < 4 Java for loop: for ( count=0; count <= 3; count += 1 )

Using a for Loop (continued) while statement could be used in place of for statement Step value: number used to increase (decrease) the loop control variable on each pass through a loop Programming languages can: Require a statement that indicates the step value Have a step value default of 1 Specify step value when each pass through the loop changes the loop control variable by a value other than 1

Common Loop Applications Using a loop to count and accumulate totals Examples Business reports often include totals List of real estate sold and total value Count of number of records processed keep track of number of A’s, B’s, C’s, etc. Counters and Accumulators: Counter usually is incremented by one each iteration Accumulator has some value added to it each iteration Running sum

Common Loop Applications Accumulate total real estate prices Declare numeric variable at beginning to be used as an accumulator Initialize the accumulator to 0 Read each transaction’s data record Add its value to accumulator variable Keep reading records until eof is encountered

Common Loop Applications (continued) 5 records processed Figure 5-16 Month-end real estate sales report

Figure 5-17 Flowchart and pseudocode for real estate sales report program

Common Loop Applications (continued) Use a loop to validate data When prompting a user for data, there is no guarantee that Validate data: make sure data falls within an acceptable range Example: user enters birth month If number is less than 1 or greater than 12 Display error message and stop the program Assign default value for the month Reprompt the user for valid input

Figure 5-18 Reprompting a user once after an invalid month is entered Programming Logic & Design, Sixth Edition

Programming Logic & Design, Sixth Edition This test checks to see if the user entered a value too small or too large, that is, if the value is OUtSIDE of the valid range. In RAPTOR, the test would be month >= LOW_MONTH and month <= HIGH_MONTH Figure 5-19 Reprompting a user using a loop after an invalid month is entered Programming Logic & Design, Sixth Edition

Common Loop Applications (continued) Validating a data type Validating data requires a variety of methods isNumeric() isChar() or isWhitespace() RAPTOR has a built-in procedure Is_number Your program may: Accept user data as a string Use a method to convert to correct to data type

Common Loop Applications (continued) Figure 5-21 Checking data for correct type

RAPTOR test for invalid data Programming Logic & Design, Seventh Edition

Common Loop Applications (continued) Validating reasonableness and consistency of data Many data items can be checked for reasonableness Good defensive programs try to foresee all possible inconsistencies and errors

Summary Use a loop to: Three steps must occur in every loop repeat a sequence of statements (RAPTOR symbols) Three steps must occur in every loop Initialize input variable or loop control variable Test variable (evaluate condition) Update the variable that controls the loop Nested loops: loops within loops

Summary (continued) Common mistakes made by programmers Neglecting to initialize loop control variable Neglecting to update the loop control variable Using the wrong comparison with the loop control variable Including statements inside the loop that belong outside the loop Most computer languages support a for statement for loop used with definite loop number of iterations is known while loop used with indefinite loop number of iterations is not known

Summary (continued) for loop expressions: Accumulator Counter Initialize Test Update Accumulator variable that accumulates values creating a running sum Counter Variable used to keep track of the number of occurrences of something (records, customers processed, etc.) Loops are often used to ensure user data is valid