Lesson 7 of 12

For Loops

Sometimes you know exactly how many times you want to repeat something. "Do 10 jumping jacks." "Write your name 5 times." When you know the count ahead of time, a for loop is the perfect tool.

A for loop repeats a set of steps a specific number of times. It has a built-in counter that starts at one number, ends at another, and updates automatically each time through the loop.

For Loop vs. While Loop

In the last lesson, we used a while loop and managed the counter ourselves in three separate places (setup, condition, update). A for loop packages all three into one neat structure — less code, fewer mistakes.

  • While loop: You set up, check, and update the counter separately.
  • For loop: The setup, condition, and update are all handled together.

In a flowchart, a for loop looks the same as a while loop — it still uses a diamond and a back arrow. The difference shows up in the pseudocode, where the FOR line handles everything in one place.

Example: Counting to 5

Let's count from 1 to 5 and then say "Done!" Notice how the flowchart looks like the while loop from the last lesson, but the pseudocode is cleaner.

Start SET i = 1 i <= 5? Yes OUTPUT i i = i + 1 No "Done!" End
BEGIN
  FOR i = 1 TO 5
    OUTPUT i
  END FOR
  OUTPUT "Done!"
END

Variable Watch

VariableValue
Step through to see variables

The flowchart looks just like a while loop — the diamond checks a condition and the dashed back arrow creates the repetition. But look at the pseudocode: the FOR line handles the setup (i = 1) and the limit (TO 5) all in one place. The counter updates automatically.

Here's what happens at each pass:

Loop pass i value i <= 5? Output
1st1Yes1
2nd2Yes2
3rd3Yes3
4th4Yes4
5th5Yes5
6th check6No — exit loop

When to Use For vs. While

Use a for loop when you know how many times to repeat:

  • "Print the numbers 1 to 100"
  • "Repeat this 10 times"
  • "Go through items 1 to 20"

Use a while loop when you don't know how many times — you just keep going until something changes:

  • "Keep asking until the user types 'quit'"
  • "Keep guessing until you get it right"
  • "Keep adding until the total is over 100"

Key Takeaways

  • A for loop repeats steps a specific number of times using a counter.
  • In a flowchart, it looks just like a while loop — a diamond with a back arrow.
  • The difference is in the pseudocode: FOR i = 1 TO 5 handles setup, condition, and update all in one line.
  • Use a for loop when you know the count. Use a while loop when you don't.
  • In pseudocode: FOR variable = start TO end ... END FOR