Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.

Similar presentations


Presentation on theme: "An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping."— Presentation transcript:

1 An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping

2 Objectives In this chapter, you will learn about: The loop structure Using a loop control variable Nested loops Avoiding common loop mistakes Using a for loop Common loop applications 2An Object-Oriented Approach to Programming Logic and Design

3 Understanding the Loop Structure Looping – Makes computer programming efficient and useful – One set of instructions can operate on multiple data sets 3An Object-Oriented Approach to Programming Logic and Design

4 Understanding the Loop Structure (cont’d) Loop body – Statements within a loop Loop structure – One of three basic structures in structured programming – Starts with a test of a Boolean expression – Executes as long as Boolean expression is true Referred to as repetition, iteration, or while loop 4An Object-Oriented Approach to Programming Logic and Design

5 Understanding the Loop Structure (cont’d) Example of a while loop while quantity in inventory remains low continue to order items endwhile endwhile signals where loop structure ends Structured loop has one entry and one exit point Body of loop can contain any number of statements – includes sequences, selections, and other loops 5An Object-Oriented Approach to Programming Logic and Design

6 Using a Loop Control Variable Loop control variable – Value is tested to control loop’s execution Three actions occur – Initialize loop control variable before entering loop – Test loop control variable If true, enter loop body – Alter loop control variable value in loop body So that while expression eventually evaluates false 6An Object-Oriented Approach to Programming Logic and Design

7 Using a Loop Control Variable (cont’d) Need to control number of repetitions – An infinite loop has no end Ways to control repetitions – Use a counter to create a definite (counter-controlled) loop – Use a sentinel value to create an indefinite loop 7An Object-Oriented Approach to Programming Logic and Design

8 Using a Definite Loop with a Counter Definite loop – Executes a predetermined number of times – Also called a counted loop or counter-controlled loop Counter – Numeric variable to count event occurrence – Variable usually initialized to 0 Example: Figure 4-2 on next slide 8An Object-Oriented Approach to Programming Logic and Design

9 9 Control variable initialized to 0 while expression compares count to 4 Value of count < 4, so loop body executes Displays “ Hello ” and adds 1 to count Next time count is evaluated, its value is 1 Loop body executes again, and count becomes 2 After four times, count < 4 is false, loop ends Using a definite loop with a counter

10 Using a Definite Loop with a Counter (cont’d) Methods of changing loop control variable – Incrementing Adds to variable – Decrementing Reduces variable Test whether value remains greater than a benchmark value 10An Object-Oriented Approach to Programming Logic and Design

11 Using An Indefinite Loop with a Sentinel Value Indefinite loop – Loop execution time based on user input – Loop may be performed different number of times each time program runs Priming input – First input that sets loop control variable’s first value Sentinel value – Value that signals a stop to a loop Figure 4-3 on following slide illustrates an indefinite loop 11An Object-Oriented Approach to Programming Logic and Design

12 Figure 4-3 12An Object-Oriented Approach to Programming Logic and Design An application with an indefinite loop

13 Using Nested Loops 13An Object-Oriented Approach to Programming Logic and Design Nested loops –A loop inside of another loop –Outer loop: loop that contains the other loop, or inner loop –Used when two or more variable values repeat to produce every combination of values

14 14An Object-Oriented Approach to Programming Logic and Design Example: Creating a quiz answer sheet using a nested loop

15 Avoiding Common Loop Mistakes 15An Object-Oriented Approach to Programming Logic and Design Four common 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

16 Mistake: Neglecting to Initialize the Loop Control Variable 16An Object-Oriented Approach to Programming Logic and Design Always a mistake Uninitialized variables may contain unknown values in some programming languages Program logic errors will occur Figure 4-7 (next slide) shows the correct logic for a greeting program Figure 4-8 (slide after next) shows an example of a program where the loop control variable is not initialized

17 17An Object-Oriented Approach to Programming Logic and Design Correct logic for greeting program Prompts user for a name While name continues to be anything but the value “ZZZ”, the program outputs a greeting and asks for the next name Figure 4-7

18 18An Object-Oriented Approach to Programming Logic and Design Incorrect logic for greeting program Missing loop control variable initialization Figure 4-8

19 Mistake: Neglecting to Alter the Loop Control Variable 19An Object-Oriented Approach to Programming Logic and Design Can cause a variety of errors, such as an infinite loop Figure 4-9 (next slide) provides an example of this common mistake – No names are accepted inside the loop

20 20An Object-Oriented Approach to Programming Logic and Design Incorrect logic for greeting program Loop control variable is not altered Figure 4-9

21 Mistake: Using the Wrong Comparison with the Loop Control Variable 21An Object-Oriented Approach to Programming Logic and Design Correct operators and operands must be used Could also result in wrong number of loop executions Figure 4-10 (next slide) shows an example of this common mistake

22 22An Object-Oriented Approach to Programming Logic and Design Incorrect logic for program Wrong test is made with the loop control variable Greater-than comparison is made instead of not-equal-to comparison Loop is never entered and program ends Figure 4-10

23 Mistake: Including Statements inside the Loop that Belong outside the Loop Can cause a program to perform inefficiently by unnecessarily executing the same code numerous times Figure 4-11 (next slide) demonstrates an inefficient way to produce 100 discount stickers for items – Inefficient because newPrice is calculated 100 times even though price hasn’t changed Figure 4-12 shows an improved method 23An Object-Oriented Approach to Programming Logic and Design

24 24An Object-Oriented Approach to Programming Logic and Design Inefficient way to produce 100 discount stickers for differently priced items newPrice is calculated 100 times even though price hasn’t changed Figure 4-11

25 25An Object-Oriented Approach to Programming Logic and Design Figure 4-11

26 26An Object-Oriented Approach to Programming Logic and Design Improved version of program newPrice is calculated once per new price; the calculation is moved to a better location Program performs more efficiently Figure 4-12

27 27An Object-Oriented Approach to Programming Logic and Design Figure 4-12

28 Using a for Loop 28An Object-Oriented Approach to Programming Logic and Design The for loop –Alternative to while loop –Used when the program knows exactly how many times the loop will repeat Three actions in one compact statement –Initializes loop control variable –Evaluates loop control variable –Alters loop control variable for statement looks different in various languages

29 Using a for Loop (cont’d) 29An Object-Oriented Approach to Programming Logic and Design Three possible ways to write pseudocode to display Hello four times using for and while loops Figure 4-13

30 Using a for Loop (cont’d) Step value – The amount by which the loop control variable changes after the body executes – Can be positive or negative – Does not have to be 1 Step value example: Displays “Hello” four times 30An Object-Oriented Approach to Programming Logic and Design for count = 12 to 6 step -2 output “Hello” endfor

31 Common Loop Applications Every computer program is different – Various applications use similar techniques – Loops can be used to: Accumulate totals Validate data 31An Object-Oriented Approach to Programming Logic and Design

32 Using a Loop to Accumulate Totals Business reports often include totals – Example: report of total value for real estate properties sold in the last month Accumulator – Variable used to gather or accumulate values during repetitions – Must be initialized prior to entering loop – Value added to current value during each repetition – Value is output at end of processing Example: Figure 4-15 on next slide 32An Object-Oriented Approach to Programming Logic and Design

33 33An Object-Oriented Approach to Programming Logic and Design Flowchart and pseudocode for real estate sales report program Figure 4-15

34 Using a Loop to Validate Data Defensive programming – prepare for all possible errors before they occur Can use loops to validate data – Make sure data is meaningful and useful – Could involve checking data type or range Example program: user enters birth month number – Possible actions if input is less than one or greater than 12 Display error message and stop the program Assign default value for month before proceeding Reprompt user for valid input – See Figure 4-16 on next slide 34An Object-Oriented Approach to Programming Logic and Design

35 35An Object-Oriented Approach to Programming Logic and Design Reprompting user once after an invalid month is entered User still may enter invalid data Better to use a loop to prompt until user enters valid data Figure 4-16

36 Limiting a Reprompting Loop Reprompting – Can help ensure invalid data – May frustrate or annoy the user if it is continuous Good programming practice – State the valid values in the prompt – Limit the number of attempts – Force (override) the input to a specific value after a certain number of attempts Example: Figure 4-18 on next slide 36An Object-Oriented Approach to Programming Logic and Design

37 37An Object-Oriented Approach to Programming Logic and Design Program limits the number of times the user can input the month of their birth Figure 4-18

38 Validating a Data Type Validating date requires a variety of methods Some programming languages have prewritten methods to check data type – Examples: isNumeric() isChar() isWhitespace() isUpper() Example: Figure 4-19 on next slide 38An Object-Oriented Approach to Programming Logic and Design

39 39An Object-Oriented Approach to Programming Logic and Design Sample program: Checking data for correct type Uses method isNumeric() to determine if the user’s input is a number Reprompts the user until input is a number Figure 4-19

40 Validating Reasonableness and Consistency of Data Good programming practice to validate data – Valid data is not necessarily correct – The more accurate the data, the more useful the output Examples of checks that can be made – Compare zip code with city – Compare date of a purchase and date of payment – If a customer’s title is “Ms.,” gender should be “F” 40An Object-Oriented Approach to Programming Logic and Design

41 Summary When a loop is used in a computer program, one set of instructions operates on multiple, separate sets of data Three steps must occur (in every loop) – Initialize loop control variable – Compare control variable to value determining when loop stops – Alter the loop control variable Nested loops are loops within loops; two control variables are used and altered at the appropriate time 41An Object-Oriented Approach to Programming Logic and Design

42 Summary (cont’d) Common loop mistakes – 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 for statement: used with definite loops – Uses a loop control variable that is automatically initialized, evaluated and incremented Loops: used in many applications to accumulate data and to ensure that user data entries are valid and reasonable 42An Object-Oriented Approach to Programming Logic and Design


Download ppt "An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping."

Similar presentations


Ads by Google