Programming Fundamentals/Loops/Nested Loops
Appearance
Nested loops have one loop control structure enclosed by another loop control structure, usually indicated through different indentation levels within the source code.[1] This activity introduces nested loops. This activity will help you understand how to use nested loops in a program.
Objectives
[edit | edit source]- Understand nested loop concepts.
- Understand how nested loops are specified in a program.
- Single-step through a program to observe nested loop execution.
Prerequisites
[edit | edit source]Learners should already be familiar with while loops, do loops, and for loops.
Introduction
[edit | edit source]Review the flowchart example on the right.
Questions
[edit | edit source]- How are nested loops structured?
- What is the expected output of this program?
Activity
[edit | edit source]With a partner, perform the following:
- Using a visual programming language, create a program similar to the flowchart on the right based on the following steps.
- Start by creating a for loop that counts from 0 to 9 by 1.
- Save the program.
- Test the program to verify that it works correctly.
- Trade places, so that both partners have an opportunity to "drive" the visual programming environment.
- Modify the program to count from 00 to 99 by 1 using nested for loops.
- Test the program to verify that it works correctly.
- Change the environment to use a slow run speed and/or step through the program one shape at a time.
- Modify the program to enclose the nested for loops inside a do loop. Ask the user if they want to count from 00 to 99 again. Continue looping while they answer "y".
- Test the program to verify that it works correctly.
- Working together, create a list of changes that might be made to use nested loops in programs you've already written. What loop types would you use, what parts could be repeated, and how would the loop terminate?
Applications
[edit | edit source]- Identify specific steps which must be followed when creating a program using nested loops.
- Discuss your activity experience with your classmates. What surprised you? What have you learned that you can apply to your own school or work environment?