Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objectives In this chapter, you will learn about:

Similar presentations


Presentation on theme: "Objectives In this chapter, you will learn about:"— Presentation transcript:

1 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

2 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.

3 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

4 Figure 5-1 The loop structure (pre-test loop)
Our book calls this a while loop

5 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

6 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

7 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 A counter-controlled while loop

8 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.

9 Must the condition be true or false for the loop body to be executed?
In RAPTOR, what would the condition be? Figure An indefinite while loop that displays “Hello” as long as the user wants to continue

10 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

11 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

12 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 Flowchart and pseudocode for AnswerSheet program

13 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

14 Figure Incorrect logic for greeting program because the loop control variable initialization is missing

15 Programming Logic & Design, Sixth Edition
Figure Incorrect logic for greeting program because the loop control variable is not altered Programming Logic & Design, Sixth Edition

16 Programming Logic & Design, Sixth Edition
For a sentinel-controlled loop the only operators you should use in the condition are = or != Figure Incorrect logic for greeting program because the wrong test is used in the condition Programming Logic & Design, Sixth Edition

17 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

18 Figure 5-13 Inefficient way to produce 100 discount price stickers for differently priced items

19 Figure 5-14 Improved discount sticker-making program

20 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

21 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, equals 4 ) Increases count by 1 (update) while loop: count = 0 while count <= or while count < 4 Java for loop: for ( count=0; count <= 3; count += 1 )

22 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

23 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

24 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

25 Common Loop Applications (continued)
5 records processed Figure Month-end real estate sales report

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

27 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

28 Figure 5-18 Reprompting a user once after an invalid month is entered
Programming Logic & Design, Sixth Edition

29 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 Reprompting a user using a loop after an invalid month is entered Programming Logic & Design, Sixth Edition

30 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

31 Common Loop Applications (continued)
Figure Checking data for correct type

32 RAPTOR test for invalid data
Programming Logic & Design, Seventh Edition

33 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

34 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

35 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

36 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


Download ppt "Objectives In this chapter, you will learn about:"

Similar presentations


Ads by Google