Programming Fundamentals/Loops/Nested Loops

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
  • 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

Learners should already be familiar with while loops, do loops, and for loops.

Introduction

edit
 
Flowgorithm nested loops

Review the flowchart example on the right.

Questions

edit
  • How are nested loops structured?
  • What is the expected output of this program?

Activity

edit

With a partner, perform the following:

  1. Using a visual programming language, create a program similar to the flowchart on the right based on the following steps.
  2. Start by creating a for loop that counts from 0 to 9 by 1.
  3. Save the program.
  4. Test the program to verify that it works correctly.
  5. Trade places, so that both partners have an opportunity to "drive" the visual programming environment.
  6. Modify the program to count from 00 to 99 by 1 using nested for loops.
  7. Test the program to verify that it works correctly.
  8. Change the environment to use a slow run speed and/or step through the program one shape at a time.
  9. 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".
  10. Test the program to verify that it works correctly.
  11. 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
  • 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?

References

edit