Programming Logic and Design Fifth Edition, Comprehensive - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

Programming Logic and Design Fifth Edition, Comprehensive

Description:

Title: Chapter 5 Created Date: 9/27/2002 11:29:22 PM Document presentation format: On-screen Show (4:3) Other titles: Times New Roman Arial Courier New Arial Unicode ... – PowerPoint PPT presentation

Number of Views:125
Avg rating:3.0/5.0
Slides: 51
Provided by: webCerrit2
Category:

less

Transcript and Presenter's Notes

Title: Programming Logic and Design Fifth Edition, Comprehensive


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

2
Objectives
  • Learn about the advantages of looping
  • Control loops with counters and sentinel values
  • Nest loops
  • Learn to avoid common loop mistakes

3
Objectives (continued)
  • Use a for loop
  • Use posttest loops
  • Recognize the characteristics shared by all loops
  • Learn about common loop applications

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

5
Understanding the Advantages of Looping
(continued)
Figure 5-1 The while loop
6
Controlling Loops with Counters and Sentinel
Values
  • As long as a Boolean expression remains true,
    while loops body executes
  • Must control number of repetitions to avoid an
    infinite loop
  • Repetitions controlled by
  • Counter
  • Sentinel value

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

8
Using a Definite while Loop with a Counter
(continued)
Figure 5-2 A while loop that prints Hello four
times
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

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

11
Figure 5-3 Looping bank balance program
12
Using an Indefinite while Loop with a Sentinel
Value (continued)
Figure 5-4 Typical execution of the looping bank
balance program
13
Using an Indefinite while Loop with a Sentinel
Value (continued)
Figure 5-5 Crucial steps that must occur in
every loop
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

15
Figure 5-7 Flowchart and pseudocode for
AnswerSheet program
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

17
Mixing Constant and Variable Sentinel Values
(continued)
Figure 5-8 Program that produces 100 labels for
every employee
18
Mixing Constant and Variable Sentinel Values
(continued)
Figure 5-8 Program that produces 100 labels for
every employee (continued)
19
Figure 5-9 Program that produces a variable
number of labels for every employee
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

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

22
Figure 5-10 Incorrect logic when loop control
variable initializations are removed from
label-making program
23
Avoiding Common Loop Mistakes (continued)
Figure 5-10 Incorrect logic when loop control
variable altering statements are removed from
label-making program (continued)
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

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

26
Avoiding Common Loop Mistakes (continued)
  • Example
  • Correct loop performed 10 times
  • counter 0
  • while counter lt 10
  • print Hello
  • counter counter 1
  • end while

27
Avoiding Common Loop Mistakes (continued)
  • Example (continued)
  • Error loop performed 11 times
  • counter 0
  • while counter lt 10
  • print Hello
  • counter counter 1
  • end while

28
Avoiding Common Loop Mistakes (continued)
  • Mistake including statements inside the loop
    that belong outside the loop
  • Example calculating a users 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

29
Figure 5-12 Pay rate projection program
30
Figure 5-14 Improved pay rate projection program
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

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

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

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

35
Using Posttest Loops (continued)
Figure 5-15 Inner loop from label production
program in Figure 5-9
36
Using Posttest Loops (continued)
Figure 5-16 Label production program using a
do-until loop
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

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

39
Recognizing the Characteristics Shared by All
Loops (continued)
Figure 5-17 Examples of unstructured loops
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

41
Common Loop Applications (continued)
  • Accumulate total real estate prices
  • Declare numeric variable at beginning
  • Initialize the accumulator to 0
  • Read each transactions 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

42
Common Loop Applications (continued)
Figure 5-18 Month-end real estate sales report
43
Figure 5-19 Flowchart and pseudocode for real
estate sales report program
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

45
Common Loop Applications (continued)
Figure 5-20 Reprompting a user once after an
invalid month is entered
46
Common Loop Applications (continued)
Figure 5-21 Reprompting a user continuously
after an invalid month is entered
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

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

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

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
Write a Comment
User Comments (0)
About PowerShow.com