ch05 loops[1]

Upload: belenj1

Post on 08-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Ch05 Loops[1]

    1/46

    PROGRAMMING LOGIC AND DESIGN

    FIFTH EDITION, COMPREHENSIVE

    Chapter 5: Looping

  • 8/7/2019 Ch05 Loops[1]

    2/46

    Objectives

    Programming Logic and Design, Fifth Edition, Comprehensive

    2

    Learn about the advantages of looping

    Control loops with counters and sentinel values

    Nest loops

    Learn to avoid common loop mistakes

    Use a for loop

    Use posttest loops

    Recognize the characteristics shared by all loops

    Learn about common loop applications

  • 8/7/2019 Ch05 Loops[1]

    3/46

    Understanding the Advantages of Looping

    Programming Logic and Design, Fifth Edition, Comprehensive

    3

    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

    Figure 5-1 The while loop

  • 8/7/2019 Ch05 Loops[1]

    4/46

    Controlling Loops with Counters and Sentinel Values

    Programming Logic and Design, Fifth Edition, Comprehensive

    4

    As long as a Boolean expression remains true,

    whileloops body executes

    Must control number of repetitions to avoid an

    infinite loop

    Repetitions controlled by

    Counter

    Sentinel value

  • 8/7/2019 Ch05 Loops[1]

    5/46

    Using a Definite while Loop with a Counter

    Programming Logic and Design, Fifth Edition, Comprehensive

    5

    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/7/2019 Ch05 Loops[1]

    6/46

    Using a Definite while Loop with a Counter(continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    6

    Figure 5-2 A whileloop that prints Hello four times

    Loop control variable is initialized prior to entering the loop

    Loop control variable is testedIf result is true, loop body entered

    Loop control variable must be altered in loop body

  • 8/7/2019 Ch05 Loops[1]

    7/46

    Using a Definite while Loop with a Counter(continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    7

    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

  • 8/7/2019 Ch05 Loops[1]

    8/46

    Using an Indefinite while Loop with a Sentinel Value

    Programming Logic and Design, Fifth Edition, Comprehensive

    8

    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

  • 8/7/2019 Ch05 Loops[1]

    9/46Programming Logic and Design, Fifth Edition, Comprehensive9

    Figure 5-3 Looping bank balance program

  • 8/7/2019 Ch05 Loops[1]

    10/46

    Using an Indefinite while Loop

    with a Sentinel Value (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    10

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

  • 8/7/2019 Ch05 Loops[1]

    11/46

    Using an Indefinite while Loop with a Sentinel Value

    Programming Logic and Design, Fifth Edition, Comprehensive

    11

    Figure 5-5

    Crucial steps

    that must

    occur in everyloop.

  • 8/7/2019 Ch05 Loops[1]

    12/46

    Nested Loops

    Programming Logic and Design, Fifth Edition, Comprehensive

    12

    Nested loops:

    loops within loops

    Outer loop:

    loop that contains another loop

    Inner loop:

    loop that is contained

    Needed when values of two (or more) variablesrepeat to produce every combination of values

  • 8/7/2019 Ch05 Loops[1]

    13/46Programming Logic and Design, Fifth Edition, Comprehensive

    13

    Figure 5-7 Flowchart and pseudocode for AnswerSheet program

    The program creates an answer sheet for an exam that contains 5 partswith three questions in each part.

  • 8/7/2019 Ch05 Loops[1]

    14/46

    Mixing Constant and Variable Sentinel Values

    Programming Logic and Design, Fifth Edition, Comprehensive

    14

    Number of times a loop executes can depend on aconstant or a value that varies

    May not want to repeat every pass through a loopthe same number of times

    Examples:

    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 employeeOuter loop controlled by value of employee name

    Inner loop controlled by production level

  • 8/7/2019 Ch05 Loops[1]

    15/46

    Figure 5-8

    Programming Logic and Design, Fifth Edition, Comprehensive

    15

    Mixing Constant

    and Variable

    Sentinel Values

    Program that

    produces 100 labels

    for every employee

  • 8/7/2019 Ch05 Loops[1]

    16/46

    Mixing Constant and Variable Sentinel Values(continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    16

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

  • 8/7/2019 Ch05 Loops[1]

    17/46

    Figure 5-9

    Programming Logic and Design, Fifth Edition, Comprehensive

    17

    Mixing Constant

    and Variable

    Sentinel Values

    Program that

    produces a variable

    number of labels for

    every employee

  • 8/7/2019 Ch05 Loops[1]

    18/46

    Avoiding Common Loop Mistakes

    Programming Logic and Design, Fifth Edition, Comprehensive

    18

    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

  • 8/7/2019 Ch05 Loops[1]

    19/46

    Avoiding Common Loop Mistakes (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    19

    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

  • 8/7/2019 Ch05 Loops[1]

    20/46

    Figure 5-10

    Programming Logic and Design, Fifth Edition, Comprehensive

    20

    Avoiding

    Common Loop

    Mistakes (continued)

    Incorrect logic when

    loop control variable

    initializations are

    removed from label-

    making program

  • 8/7/2019 Ch05 Loops[1]

    21/46

    Avoiding Common Loop Mistakes (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    21

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

  • 8/7/2019 Ch05 Loops[1]

    22/46

    Avoiding Common Loop Mistakes (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    22

    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 incrementslabelCounter

    Inner loop executes infinitely

    Always incorrect to create a loop that cannot

    terminate

  • 8/7/2019 Ch05 Loops[1]

    23/46

    Avoiding Common Loop Mistakes (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    23

    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

  • 8/7/2019 Ch05 Loops[1]

    24/46

    Avoiding Common Loop Mistakes (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    24

    Example:

    Correct: loop performed 10 times

    counter = 0

    while counter < 10

    print Hello

    counter = counter + 1

    end while

  • 8/7/2019 Ch05 Loops[1]

    25/46

    Avoiding Common Loop Mistakes (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    25

    Example (continued):

    Error: loop performed 11 times

    counter = 0

    while counter

  • 8/7/2019 Ch05 Loops[1]

    26/46

    Avoiding Common Loop Mistakes (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    26

    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

  • 8/7/2019 Ch05 Loops[1]

    27/46

    Programming Logic and Design, Fifth Edition, Comprehensive

    27

    Figure 5-12

    Pay rate

    projection

    program

  • 8/7/2019 Ch05 Loops[1]

    28/46

    Programming Logic and Design, Fifth Edition, Comprehensive

    28

    Figure 5-14

    Improved

    pay rate

    projectionprogram

  • 8/7/2019 Ch05 Loops[1]

    29/46

    Using a for Loop

    Programming Logic and Design, Fifth Edition, Comprehensive

    29

    for statement or for loop is a definite loop

    Provides three actions in one structure

    Initializes

    Evaluates Increments

    Takes the form:

    forvariable = initialValuetofinalValue

    do something

    endfor

  • 8/7/2019 Ch05 Loops[1]

    30/46

    Using a for Loop (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    30

    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

  • 8/7/2019 Ch05 Loops[1]

    31/46

  • 8/7/2019 Ch05 Loops[1]

    32/46

    Using Posttest Loops

    Programming Logic and Design, Fifth Edition, Comprehensive

    32

    Loop body may never execute in while loop and

    for loop

    Use posttest loop when loop body must execute at

    least once do-untilloop

    do-while loop

    do-until loop executes until condition is true do-while loop executes until condition is false

  • 8/7/2019 Ch05 Loops[1]

    33/46

    Using Posttest Loops (continued)33

    Programming Logic and Design, Fifth Edition, Comprehensive

    Figure 5-15 Inner loop from label

    production program in Figure 5-9

    Figure 5-16 Label production

    program using a do-until loop

  • 8/7/2019 Ch05 Loops[1]

    34/46

    Recognizing the Characteristics Shared by All Loops

    Programming Logic and Design, Fifth Edition, Comprehensive

    34

    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-untilloop Loop-controlling question placed at end of steps that

    repeat

  • 8/7/2019 Ch05 Loops[1]

    35/46

    Recognizing the Characteristics Shared by All Loops (cont.)

    Characteristics of all

    structured loops:

    Loop-controlling

    question must provide

    entry or exit from

    repeating structure

    Loop-controlling

    question provides the

    onlyentry to or exitfrom the repeating

    structure

    Exactly one loop-

    controlling value

    Provides only entry to or

    exit from the loop

    35

    Programming Logic and Design, Fifth Edition, Comprehensive

  • 8/7/2019 Ch05 Loops[1]

    36/46

    Common Loop Applications

    Programming Logic and Design, Fifth Edition, Comprehensive

    36

    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

  • 8/7/2019 Ch05 Loops[1]

    37/46

    Common Loop Applications (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    37

    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

  • 8/7/2019 Ch05 Loops[1]

    38/46

    Common Loop Applications (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    38

    Figure 5-18

    Month-end

    real estate

    sales report

  • 8/7/2019 Ch05 Loops[1]

    39/46

    Programming Logic and Design, Fifth Edition, Comprehensive

    39

    Figure 5-19

    Flowchart

    and

    pseudocode

    for real

    estate sales

    report

    program

  • 8/7/2019 Ch05 Loops[1]

    40/46

    Common Loop Applications (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    40

    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 acceptableranges

    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

  • 8/7/2019 Ch05 Loops[1]

    41/46

    Common Loop Applications (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    41

    Figure 5-20

    Reprompting

    a user once

    after an

    invalid

    month is

    entered

  • 8/7/2019 Ch05 Loops[1]

    42/46

    Common Loop Applications (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    42

    Figure 5-21

    Reprompting

    a user

    continuously

    after an

    invalid

    month is

    entered

  • 8/7/2019 Ch05 Loops[1]

    43/46

    Summary

    Programming Logic and Design, Fifth Edition, Comprehensive

    43

    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 controlvariables

    Alter each at the appropriate time

  • 8/7/2019 Ch05 Loops[1]

    44/46

    Summary (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    44

    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

  • 8/7/2019 Ch05 Loops[1]

    45/46

    Summary (continued)

    Programming Logic and Design, Fifth Edition, Comprehensive

    45

    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

  • 8/7/2019 Ch05 Loops[1]

    46/46

    Summary (continued)

    46

    Characteristics of all structured loops:

    Loop-controlling question provides entry or exit from

    repeating structure

    Loop-controlling question provides the only entry or exitfrom repeating structure

    Accumulator: variable that gathers values

    Loops used to ensure user data is valid by

    reprompting the user