programming logic and design fifth edition, comprehensive chapter 5 looping

50
Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Upload: catherine-freeman

Post on 16-Jan-2016

233 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design

Fifth Edition, Comprehensive

Chapter 5Looping

Page 2: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 2

Objectives

• Learn about the advantages of looping

• Control loops with counters and sentinel values

• Nest loops

• Learn to avoid common loop mistakes

Page 3: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 3

Objectives (continued)

• Use a for loop

• Use posttest loops

• Recognize the characteristics shared by all loops

• Learn about common loop applications

Page 4: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 4

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

Page 5: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 5

Understanding the Advantages of Looping (continued)

Figure 5-1 The while loop

Page 6: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 6

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

Page 7: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 7

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

Page 8: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 8

Using a Definite while Loop with a Counter (continued)

Figure 5-2 A while loop that prints “Hello” four times

Page 9: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 9

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

Page 10: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 10

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

Page 11: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 11

Figure 5-3 Looping bank balance program

Page 12: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 12

Using an Indefinite while Loop with a Sentinel Value (continued)

Figure 5-4 Typical execution of the looping bank balance program

Page 13: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 13

Using an Indefinite while Loop with a Sentinel Value (continued)

Figure 5-5 Crucial steps that must occur in every loop

Page 14: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 14

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

Page 15: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 15

Figure 5-7 Flowchart and pseudocode for AnswerSheet program

Page 16: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 16

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• Outer loop controlled by value of employee name• Inner loop controlled by production level

Page 17: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 17

Mixing Constant and Variable Sentinel Values (continued)

Figure 5-8 Program that produces 100 labels for every employee

Page 18: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 18

Mixing Constant and Variable Sentinel Values (continued)

Figure 5-8 Program that produces 100 labels for every employee (continued)

Page 19: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 19

Figure 5-9 Program that produces a variable number of labels for every employee

Page 20: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 20

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

Page 21: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 21

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

Page 22: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 22

Figure 5-10 Incorrect logic when loop control variable initializations are removed from label-making program

Page 23: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 23

Avoiding Common Loop Mistakes (continued)

Figure 5-10 Incorrect logic when loop control variable altering statements are removed from label-making program (continued)

Page 24: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 24

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

• Inner loop executes infinitely

• Always incorrect to create a loop that cannot terminate

Page 25: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 25

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

Page 26: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 26

Avoiding Common Loop Mistakes (continued)

• Example:– Correct: loop performed 10 times

counter = 0

while counter < 10

print “Hello”

counter = counter + 1

end while

Page 27: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 27

Avoiding Common Loop Mistakes (continued)

• Example (continued):– Error: loop performed 11 times

counter = 0

while counter <= 10

print “Hello”

counter = counter + 1

end while

Page 28: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 28

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

Page 29: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 29

Figure 5-12 Pay rate projection program

Page 30: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 30

Figure 5-14 Improved pay rate projection program

Page 31: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 31

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

Page 32: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 32

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

Page 33: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 33

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

Page 34: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 34

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

Page 35: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 35

Using Posttest Loops (continued)

Figure 5-15 Inner loop from label production program in Figure 5-9

Page 36: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 36

Using Posttest Loops (continued)

Figure 5-16 Label production program using a do-until loop

Page 37: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 37

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

Page 38: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 38

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

Page 39: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 39

Recognizing the Characteristics Shared by All Loops (continued)

Figure 5-17 Examples of unstructured loops

Page 40: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 40

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

Page 41: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 41

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

Page 42: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 42

Common Loop Applications (continued)

Figure 5-18 Month-end real estate sales report

Page 43: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 43

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

Page 44: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 44

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

Page 45: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 45

Common Loop Applications (continued)

Figure 5-20 Reprompting a user once after an invalid month is entered

Page 46: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 46

Common Loop Applications (continued)

Figure 5-21 Reprompting a user continuously after an invalid month is entered

Page 47: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 47

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

Page 48: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 48

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

Page 49: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 49

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

Page 50: Programming Logic and Design Fifth Edition, Comprehensive Chapter 5 Looping

Programming Logic and Design, Fifth Edition, Comprehensive 50

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