Programming Fundamentals/Loops/For Loops

A for loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly based on given parameters. For loops are typically used when the number of iterations is known before entering the loop. A for loop can be thought of as shorthand for a while loop which increments and tests a loop variable. This activity introduces for loops. This activity will help you understand how to use for loops in a program.

Objectives

 * Understand for loop concepts.
 * Understand how for loops are specified in a program.
 * Understand the difference between while loops and for loops and when to use each one.
 * Single-step through a program to observe for loop execution.

Prerequisites
Learners should already be familiar with while loops.

Introduction


Review the flowchart example on the right.

Questions

 * What flowcharting symbol is used to indicate a for loop?
 * How are for loops structured?
 * What is the difference between a while loop and a for loop?
 * When would you want to use a while loop vs. a for loop?

Activity
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 1 to 5 by 1.
 * 3) Save the program.
 * 4) Test the program to verify that it works correctly.
 * 5) Modify the program to count from 1 to 10 by 1.
 * 6) Modify the program to count from 5 to 10 by 1.
 * 7) Modify the program to count from 0 to 10 by 2.
 * 8) Trade places, so that both partners have an opportunity to "drive" the visual programming environment.
 * 9) Modify the program to count from any start value the user enters to 10 by 1.
 * 10) Modify the program to count from any start value the user enters to any stop value the user enters by 1.
 * 11) Modify the program to count from any start value the user enters to any stop value the user enters by any increment value the user enters.
 * 12) Change the environment to use a slow run speed and/or step through the program one shape at a time.
 * 13) Working together, create a list of changes that might be made to use do loops in programs you've already written. What parts could be repeated and how would the loop terminate?

Applications

 * Identify specific steps which must be followed when creating a program using for 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?