Objectives In this chapter, you will learn about: Counter-controlled and sentinel controlled loops Nested loops Using a for loop Common loop applications Loop control structure in RAPTOR repeat until true rather than repeat while true
Understanding the Advantages of Looping control structure that repeats a set of actions (loop body) while some condition remains true or until some condition becomes true.
Loop Control Structure in RAPTOR In RAPTOR: you repeat the body of the loop UNTIL the condition evaluates to true. RAPTOR lets you structure your loop as one of three types: Pre-Test loop ( while / for ) Mid-Test loop illegal in our book Post-Test loop ( do … while ) Our book only shows us pre-test loops. RAPTOR Loop Symbol Note: In most languages (including Java) you repeat the loop body while the condition remains true
Figure 5-1 The loop structure (pre-test loop) Our book calls this a while loop
Looping Definite and Indefinite Loops Looping may be achieved using either a definite loop or an indefinite loop A definite loop is also referred to as a counter-controlled loop An indefinite loop is also referred to as a sentinel-controlled loop For a definite loop, the loop body will be executed a specific number of times. For an indefinite loop, the number of times the body of the loop should be executed can be different for each run of a program
Using a Counter-Controlled while loop As long as a boolean expression (the condition) remains true, the while loop’s body executes. RAPTOR keep executing UNTIL the condition becomes true Essential Steps: Create and initialize a loop control variable (lcv) Determine the upper or lower limit for the lcv Determine the step (increment or decrement) for the lcv Determine the boolean expression (condition) that will control the loop Each iteration of the loop, update the lcv
Using a Definite (Counter-Controlled) Loop Must the condition be true or false for the loop body to be executed? In RAPTOR, what would the condition be? How many times is “Hello” displayed? lcv is: count Figure 5-3 A counter-controlled while loop
Using an Indefinite Loop (Sentinel-Controlled) with a Sentinel Value May be performed a different number of times each time the program executes Essential steps: Identify a sentinel value (value outside the range of valid input data) that will be used as the loop exit condition name = QUIT //where QUIT is a named constant sentinel value End_of_input //RAPTOR sentinel module expression Java hasNext( ) == false //Java method to evaluate end of input condition Each iteration of the loop get a new input value to compare to the sentinel value.
Must the condition be true or false for the loop body to be executed? In RAPTOR, what would the condition be? Figure 5-4 An indefinite while loop that displays “Hello” as long as the user wants to continue
Understanding the Loop in a Program’s Mainline Logic Three steps that should occur in every properly functioning loop Initialize the variable that will control the loop ( sentinel or counter value ) Test the condition to determine whether the loop body executes Update (aka alter) the loop control variable increment/decrement the lcv get a new input value to compare to the sentinel value
Nested Loops Nested loops: Outer loop: Inner loop: loop within another loop 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
Figure 5-8 Flowchart and pseudocode for AnswerSheet program Must the condition be true or false for the loop body to be executed? In RAPTOR, what would the condition be? RAPTOR / Java <= versus > = versus != > versus <= “flip” the operator! Figure 5-8 Flowchart and pseudocode for AnswerSheet program
Common Loop Mistakes Neglecting to initialize the loop control variable Neglecting to update the loop control variable Loop executes one too many or one too few times operator: < or <= OR > or >= number of iterations = Last used – First used + 1 Including statements inside the loop that belong outside the loop
Figure 5-10 Incorrect logic for greeting program because the loop control variable initialization is missing
Programming Logic & Design, Sixth Edition Figure 5-10 Incorrect logic for greeting program because the loop control variable is not altered Programming Logic & Design, Sixth Edition
Programming Logic & Design, Sixth Edition For a sentinel-controlled loop the only operators you should use in the condition are = or != Figure 5-12 Incorrect logic for greeting program because the wrong test is used in the condition Programming Logic & Design, Sixth Edition
Avoiding Common Loop Mistakes (continued) including statements inside the loop that belong outside the loop Example: discount every item by 30 percent Inefficient because the same value is calculated 100 separate times for each price that is entered Move outside loop for efficiency
Figure 5-13 Inefficient way to produce 100 discount price stickers for differently priced items
Figure 5-14 Improved discount sticker-making program
Using a for Loop for statement or for loop is a definite loop specifically, it is a pre-test loop can be used in pseudocode or a Java program Remember, keywords like while, for, do have no meaning in a flowchart! Puts all of the loop control expressions in the for loop header Initialize Test Update Takes the form: [initial, final] for loopControlVariable = initialValue to finalValue [step stepValue] do something endfor
Using a for Loop (continued) Example pseudocode for loop for count = 0 to 3 step 1 [0,3] output “Hello” end for Initializes count to 0 Checks count against the limit value 3 (test) If evaluation is true, for statement body prints the label Executes 4 times ( last=3, first=0, 3-0+1 equals 4 ) Increases count by 1 (update) while loop: count = 0 while count <= 3 or while count < 4 Java for loop: for ( count=0; count <= 3; count += 1 )
Using a for Loop (continued) while statement could be used in place of for statement Step value: number used to increase (decrease) the 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 a value other than 1
Common Loop Applications Using a loop to count and accumulate totals Examples Business reports often include totals List of real estate sold and total value Count of number of records processed keep track of number of A’s, B’s, C’s, etc. Counters and Accumulators: Counter usually is incremented by one each iteration Accumulator has some value added to it each iteration Running sum
Common Loop Applications Accumulate total real estate prices Declare numeric variable at beginning to be used as an accumulator Initialize the accumulator to 0 Read each transaction’s data record Add its value to accumulator variable Keep reading records until eof is encountered
Common Loop Applications (continued) 5 records processed Figure 5-16 Month-end real estate sales report
Figure 5-17 Flowchart and pseudocode for real estate sales report program
Common Loop Applications (continued) Use a loop to validate data When prompting a user for data, there is no guarantee that Validate data: make sure data falls within an acceptable range Example: user enters birth month If number is 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
Figure 5-18 Reprompting a user once after an invalid month is entered Programming Logic & Design, Sixth Edition
Programming Logic & Design, Sixth Edition This test checks to see if the user entered a value too small or too large, that is, if the value is OUtSIDE of the valid range. In RAPTOR, the test would be month >= LOW_MONTH and month <= HIGH_MONTH Figure 5-19 Reprompting a user using a loop after an invalid month is entered Programming Logic & Design, Sixth Edition
Common Loop Applications (continued) Validating a data type Validating data requires a variety of methods isNumeric() isChar() or isWhitespace() RAPTOR has a built-in procedure Is_number Your program may: Accept user data as a string Use a method to convert to correct to data type
Common Loop Applications (continued) Figure 5-21 Checking data for correct type
RAPTOR test for invalid data Programming Logic & Design, Seventh Edition
Common Loop Applications (continued) Validating reasonableness and consistency of data Many data items can be checked for reasonableness Good defensive programs try to foresee all possible inconsistencies and errors
Summary Use a loop to: Three steps must occur in every loop repeat a sequence of statements (RAPTOR symbols) Three steps must occur in every loop Initialize input variable or loop control variable Test variable (evaluate condition) Update the variable that controls the loop Nested loops: loops within loops
Summary (continued) Common mistakes made by programmers Neglecting to initialize loop control variable Neglecting to update the loop control variable Using the wrong comparison with the 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 loop number of iterations is known while loop used with indefinite loop number of iterations is not known
Summary (continued) for loop expressions: Accumulator Counter Initialize Test Update Accumulator variable that accumulates values creating a running sum Counter Variable used to keep track of the number of occurrences of something (records, customers processed, etc.) Loops are often used to ensure user data is valid