LSP- For Statement Lesson
For Statement
The for loop is a counter controlled loop. A counter controlled loop executes a certain number of times controlled by a counter variable. The for loop structure parts are just like a while loop. It has three main parts:
- Initializing variable that is the counter
- Condition
- Step increment/decrement
Let's compare the syntax for a while and for loop. The two programs have the same output, but the for loop streamlines the initialization, condition, and step. The relationship between the two is shown below.
The order of a for loop:
- The initialized variable is set.
- The condition is checked.
- The body of the for loop is executed.
- Step: The initialized counter variable is changed (either increment or decrement).
How to determine the initializing variable and increment
Problem: We want to draw a line starting at the top and ending at the bottom. We want the line repeated every 3 pixels.
To demonstrate how to determine the values for the loop, draw a graph.
You can see from the graph that you are drawing a line from (0,0) to (0, 12). It is repeated at every 3 pixels.
Now look for a pattern.
- The y locations do not change. They remain beginning y of 0 and ending y of 12.
- The beginning and ending x locations are the same. The next line is drawn at x + 3
- If you set the initializing variable to 0 and increment it by 3 each time through the loop it can control the x location. The y locations stay constant at 0 and 12 which is the height of the frame.
For Statements Video
Watch the for statements video below.
Remember scope refers to where a variable can be seen. In a for statement, if the initialized variable is created inside the for loop, it can only be seen inside the for loop. If it needs to be seen outside the for loop, it needs to be created outside the for loop.
Analyzing for Loops Activity
Try the Analyzing for Loops learning object below. Drag the design to the appropriate box.
[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION