PLF Lesson 3 - Looping (Continuation)
PLF Lesson 3 - Looping (Continuation)
Eighth Edition
Looping
Advantages of Looping
Week 10
Objectives
• In this chapter, you will learn about:
• The advantages of looping
• Using a loop control variable
• Nested loops
• Avoiding common loop mistakes
• Using a for loop
• Common loop applications
• The similarities and differences between selections and
loops
Figure 5-3 A counted while loop that outputs Hello four times
Figure 5-5 Typical executions of the program in Figure 5-4 in two environments
Programming Logic and Design, Eighth Edition 13
Understanding the Loop in a
Program’s Mainline Logic
• Three steps should occur in every properly
functioning loop
– Provide a starting value for the variable that will control
the loop
– Test the loop control variable to determine whether the
loop body executes
– Alter the loop control variable
Figure 5-10 Incorrect logic for greeting program because the loop control variable
initialization is missing
Programming Logic and Design, Eighth Edition 24
Avoiding Common Loop Mistakes
(continued)
Figure 5-15 Comparable while and for statements that each output Hello four times
• Example
for count = 0 to 3 step 1
output "Hello"
endfor
• Initializes count variable to 0
• Checks count variable against the limit value 3
• If evaluation is true, for statement body prints the
word “Hello”
• Increases count by 1 using a step value
Programming Logic and Design, Eighth Edition Figure 5-20 Limiting user reprompts 49
Common Loop Applications (continued)
Programming Logic and Design, Eighth Edition Figure 5-21 Checking data for correct type 51
Common Loop Applications (continued)
• Comparing Selections
and Loops
• Selection Structure
– The two logical paths
(True and False)
join together
• Loop Structure
– One of the logical
branches returns to
the same decision
Figure 5-22 Comparing a
selection and a loop
Programming Logic and Design, Eighth Edition 53
Common
Loop
Applications
(continued)
Figure 5-24 Efficient and structured logic for getting and displaying employee records