Programming Logic and Design Fifth Edition, Comprehensive

Slides:



Advertisements
Similar presentations
Programming with Microsoft Visual Basic th Edition
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
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
Programming Logic and Design, Third Edition Comprehensive
Objectives In this chapter, you will learn about:
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.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Loops and Files.
© 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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
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.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
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.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Programming Logic and Design Fifth Edition, Comprehensive
Chapter 7: The Repetition Structure Introduction to Programming with C++ Fourth Edition.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
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.
Loops Tonga Institute of Higher Education. Introduction Programs need to be able to execute tasks repeatedly. Use loops to repeat actions  For Loop 
Chapter 5: Looping. Using the while Loop Loop – A structure that allows repeated execution of a block of statements Loop body – A block of statements.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
Programming Logic and Design Fourth Edition, Comprehensive
CHAPTER 5A Loop Structure
( Iteration / Repetition / Looping )
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Topics Introduction to Repetition Structures
Learning About the Loop Structure (continued)
MSIS 655 Advanced Business Applications Programming
Chapter 8: More on the Repetition Structure
Chapter 6: Repetition Statements
Programming Logic and Design Fifth Edition, Comprehensive
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Objectives Learn about the advantages of looping Control loops with counters and sentinel values Nest loops Learn to avoid common loop mistakes Programming Logic and Design, Fifth Edition, Comprehensive

Objectives (continued) Use a for loop Use posttest loops Recognize the characteristics shared by all loops Learn about common loop applications Programming Logic and Design, Fifth Edition, Comprehensive

Understanding the Advantages of Looping Looping makes computer programming efficient and worthwhile Write one set of instructions to operate on multiple, separate sets of data Loop: structure that repeats actions while some condition continues Programming Logic and Design, Fifth Edition, Comprehensive

Understanding the Advantages of Looping (continued) Figure 5-1 The while loop Programming Logic and Design, Fifth Edition, Comprehensive

Controlling Loops with Counters and Sentinel Values As long as a Boolean expression remains true, while loop’s body executes Must control number of repetitions to avoid an infinite loop Repetitions controlled by Counter Sentinel value Programming Logic and Design, Fifth Edition, Comprehensive

Using a Definite while Loop with a Counter Three actions make a while loop end correctly: Loop control variable is initialized Prior to entering the loop Loop control variable is tested If result is true, loop body entered Loop control variable must be altered in loop body while expression eventually evaluates to false Loop control variables altered by: Incrementing Decrementing Programming Logic and Design, Fifth Edition, Comprehensive

Using a Definite while Loop with a Counter (continued) Figure 5-2 A while loop that prints “Hello” four times Programming Logic and Design, Fifth Edition, Comprehensive

Using a Definite while Loop with a Counter (continued) Definite loop: number of iterations predetermined Also called counted loop Counter: numeric variable used to count number of times an event occurs Loop control variable may be altered by user input Indefinite loop: loop iterates until some condition is true Number of iterations may vary Programming Logic and Design, Fifth Edition, Comprehensive

Using an Indefinite while Loop with a Sentinel Value Indefinite loop: loop performed a different number of times each time the program executes Three crucial steps: Starting value to control the loop must be provided Comparison must be made using the value that controls the loop Within the loop, value that controls the loop must be altered Loop control variable: any variable that determines whether the loop will continue Programming Logic and Design, Fifth Edition, Comprehensive

Figure 5-3 Looping bank balance program Programming Logic and Design, Fifth Edition, Comprehensive

Using an Indefinite while Loop with a Sentinel Value (continued) Figure 5-4 Typical execution of the looping bank balance program Programming Logic and Design, Fifth Edition, Comprehensive

Using an Indefinite while Loop with a Sentinel Value (continued) Figure 5-5 Crucial steps that must occur in every loop Programming Logic and Design, Fifth Edition, Comprehensive

Nested Loops Nested loops: loops within loops 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 Programming Logic and Design, Fifth Edition, Comprehensive

Figure 5-7 Flowchart and pseudocode for AnswerSheet program Programming Logic and Design, Fifth Edition, Comprehensive

Mixing Constant and Variable Sentinel Values Number of times a loop executes can depend on a constant or a value that varies May not want to repeat every pass through a loop the same number of times Example: Print 100 labels for every employee Outer loop controlled by value of employee name Inner loop executes 100 times Print variable number of labels for every employee Inner loop controlled by production level Programming Logic and Design, Fifth Edition, Comprehensive

Mixing Constant and Variable Sentinel Values (continued) Figure 5-8 Program that produces 100 labels for every employee Programming Logic and Design, Fifth Edition, Comprehensive

Mixing Constant and Variable Sentinel Values (continued) Figure 5-8 Program that produces 100 labels for every employee (continued) Programming Logic and Design, Fifth Edition, Comprehensive

Figure 5-9 Program that produces a variable number of labels for every employee Programming Logic and Design, Fifth Edition, Comprehensive

Avoiding Common Loop Mistakes Neglecting to initialize the loop control variable Neglecting to alter the loop control variable Using the wrong comparison with the loop control variable Including statements inside the loop that belong outside the loop Programming Logic and Design, Fifth Edition, Comprehensive

Avoiding Common Loop Mistakes (continued) Mistake: neglecting to initialize the loop control variable Example: get name statement removed Value of name unknown or garbage Program may end before any labels printed 100 labels printed with an invalid name labelCounter = 0 statement removed Value of labelCounter unpredictable Loop might not execute If automatically initialized to zero, only first labels printed Programming Logic and Design, Fifth Edition, Comprehensive

Figure 5-10 Incorrect logic when loop control variable initializations are removed from label-making program Programming Logic and Design, Fifth Edition, Comprehensive

Avoiding Common Loop Mistakes (continued) Figure 5-10 Incorrect logic when loop control variable altering statements are removed from label-making program (continued) Programming Logic and Design, Fifth Edition, Comprehensive

Avoiding Common Loop Mistakes (continued) Mistake: neglecting to alter the loop control variable Remove get name instruction from outer loop User never enters a name after the first one Inner loop executes infinitely Remove the statement that increments labelCounter Always incorrect to create a loop that cannot terminate Programming Logic and Design, Fifth Edition, Comprehensive

Avoiding Common Loop Mistakes (continued) Mistake: using the wrong comparison with the loop control variable Programmers must use correct comparison Off-by-one error Seriousness depends on actions performed within a loop Overcharge insurance customer by one month Overbook a flight on airline application Dispense extra medication to patients in pharmacy Programming Logic and Design, Fifth Edition, Comprehensive

Avoiding Common Loop Mistakes (continued) Example: Correct: loop performed 10 times counter = 0 while counter < 10 print “Hello” counter = counter + 1 end while Programming Logic and Design, Fifth Edition, Comprehensive

Avoiding Common Loop Mistakes (continued) Example (continued): Error: loop performed 11 times counter = 0 while counter <= 10 print “Hello” counter = counter + 1 end while Programming Logic and Design, Fifth Edition, Comprehensive

Avoiding Common Loop Mistakes (continued) Mistake: including statements inside the loop that belong outside the loop Example: calculating a user’s projected weekly pay raise Value of weeklyPay recalculated on every pass through the loop, although it does not change Inefficient, especially for complicated calculations or large numbers of calculations Programming Logic and Design, Fifth Edition, Comprehensive

Figure 5-12 Pay rate projection program Programming Logic and Design, Fifth Edition, Comprehensive

Figure 5-14 Improved pay rate projection program Programming Logic and Design, Fifth Edition, Comprehensive

Using a for Loop for statement or for loop is a definite loop Provides three actions in one structure Initializes Evaluates Increments Takes the form: for initialValue to finalValue do something endfor Programming Logic and Design, Fifth Edition, Comprehensive

Using a for Loop (continued) Example: for count = 0 to 99 print LABEL_TEXT, name endfor Initializes count to 0 Checks count against the limit value 99 If evaluation is true, for statement body prints the label Increases count by 1 Programming Logic and Design, Fifth Edition, Comprehensive

Using a for Loop (continued) while statement could be used in place of for statement Step value: number used to increase a 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 value other than 1 Programming Logic and Design, Fifth Edition, Comprehensive

Using Posttest Loops Loop body may never execute in while loop and for loop Use posttest loop when loop body must execute at least once do-until loop do-while loop do-until loop executes until condition is true do-while loop executes until condition is false Programming Logic and Design, Fifth Edition, Comprehensive

Using Posttest Loops (continued) Figure 5-15 Inner loop from label production program in Figure 5-9 Programming Logic and Design, Fifth Edition, Comprehensive

Using Posttest Loops (continued) Figure 5-16 Label production program using a do-until loop Programming Logic and Design, Fifth Edition, Comprehensive

Recognizing the Characteristics Shared by All Loops Every logical problem could be solved using only the while loop Other forms are conveniences while loop Loop-controlling question placed at beginning of steps that repeat do-until loop Loop-controlling question placed at end of steps that repeat Programming Logic and Design, Fifth Edition, Comprehensive

Recognizing the Characteristics Shared by All Loops (continued) Characteristics of all structured loops: Loop-controlling question must provide entry or exit from repeating structure Loop-controlling question provides the only entry to or exit from the repeating structure Exactly one loop-controlling value Provides only entry to or exit from the loop Programming Logic and Design, Fifth Edition, Comprehensive

Recognizing the Characteristics Shared by All Loops (continued) Figure 5-17 Examples of unstructured loops Programming Logic and Design, Fifth Edition, Comprehensive

Common Loop Applications Using a loop to accumulate totals Examples: Business reports often include totals Telephone bill provides a total List of real estate sold and total value Accumulator: variable that gathers values Similar to a counter Counter increments by one Accumulator increments by some value Programming Logic and Design, Fifth Edition, Comprehensive

Common Loop Applications (continued) Accumulate total real estate prices Declare numeric variable at beginning Initialize the accumulator to 0 Read each transaction’s data record Add its value to accumulator variable Read the next record until eof Variables exist only for the life of the application Run the application a second time, variables occupy different memory location Programming Logic and Design, Fifth Edition, Comprehensive

Common Loop Applications (continued) Figure 5-18 Month-end real estate sales report Programming Logic and Design, Fifth Edition, Comprehensive

Figure 5-19 Flowchart and pseudocode for real estate sales report program Programming Logic and Design, Fifth Edition, Comprehensive

Common Loop Applications (continued) Using a loop to validate data When prompting a user for data, no guarantee that data is valid Validate data: make sure data falls in acceptable ranges Example: user enters birth month If number 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 Programming Logic and Design, Fifth Edition, Comprehensive

Common Loop Applications (continued) Figure 5-20 Reprompting a user once after an invalid month is entered Programming Logic and Design, Fifth Edition, Comprehensive

Common Loop Applications (continued) Figure 5-21 Reprompting a user continuously after an invalid month is entered Programming Logic and Design, Fifth Edition, Comprehensive

Summary When using a loop, write one set of instructions that operates on multiple, separate data Three steps must occur in every loop: Initialize loop control variable Compare variable to some value Alter the variable that controls the loop Nested loops: loops within loops Nested loops maintain two individual loop control variables Alter each at the appropriate time Programming Logic and Design, Fifth Edition, Comprehensive

Summary (continued) Common mistakes made by programmers: Neglecting to initialize loop control variable Neglecting to alter loop control variable Using wrong comparison with 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 loops When number of iterations is known Programming Logic and Design, Fifth Edition, Comprehensive

Summary (continued) for loop automatically: Initializes Evaluates Increments Use posttest loop when loop body must execute at least one time Control variable evaluated after loop body executes Programming Logic and Design, Fifth Edition, Comprehensive

Summary (continued) Characteristics of all structured loops: Loop-controlling question provides entry or exit from repeating structure Loop-controlling question provides the only entry or exit from repeating structure Accumulator: variable that gathers values Loops used to ensure user data is valid by reprompting the user Programming Logic and Design, Fifth Edition, Comprehensive