Foreach Loops
Imagine you have a playlist of songs. You don't say "play song number 1, then play song number 2, then play song number 3..." — you just hit play and it goes through each song in the list automatically. That's a foreach loop.
A foreach loop goes through a list of items, one at a time, and does something with each one. You don't need to count or track a number — it automatically picks up the next item until the list is empty.
Foreach vs. While — What's the Difference?
A while loop keeps going as long as a condition is true. You have to set up a counter, check it, and update it yourself.
A foreach loop is simpler: "for each item in this list, do something." The loop handles all the counting behind the scenes. You just focus on what to do with each item.
| While Loop | Foreach Loop |
|---|---|
| You manage a counter variable | The loop manages the position for you |
| Good for "repeat N times" | Good for "do this to every item in a list" |
| Risk of infinite loops | Always stops when the list ends |
How It Looks in a Flowchart
A foreach loop in a flowchart looks similar to a while loop — there's still a diamond and a back arrow. The diamond asks: "Are there more items in the list?" If yes, it grabs the next item and does something with it. If no, the loop ends.
Example: Class Roll Call
A teacher has a list of student names: Alice, Bob, Charlie. The program goes through each name and says it out loud. Step through to see how the foreach loop picks up each name, one at a time.
BEGIN
names = ["Alice", "Bob", "Charlie"]
FOR EACH name IN names
OUTPUT name
END FOR EACH
OUTPUT "Roll call done!"
END
Variable Watch
| Variable | Value |
|---|---|
| Step through to see variables | |
Here's what happens on each pass through the loop:
| Loop pass | Current name | Output |
|---|---|---|
| 1st | Alice | Alice |
| 2nd | Bob | Bob |
| 3rd | Charlie | Charlie |
| 4th check | — | No more names — exit loop |
Notice how simple the pseudocode is: FOR EACH name IN names.
That's it! No counter, no "count = count + 1" — the foreach loop
takes care of moving through the list for you. Compare that to the while loop
from the last lesson — much simpler, right?
When to Use Foreach
Use a foreach loop when you have a collection of things (a list of names, a set of scores, items in a shopping cart) and you want to do the same action to every item. Some real-world examples:
- Play each song in a playlist
- Check each answer on a quiz
- Send a message to each friend in your contacts
- Calculate the total by adding up each price in a shopping cart
Important rule: don't change the list while looping through it! During a foreach loop, you should never add or remove items from the list you're looping through. Why? The loop is keeping track of where it is in the list. If you add or remove items, the list shifts around and the loop gets confused — it might skip items, repeat items, or crash the program.
Think of it like a teacher reading names off a paper roll call sheet:
- If someone adds a name in the middle of the sheet while the teacher is reading, the teacher might skip a name or read one twice.
- If someone crosses out a name that the teacher hasn't reached yet, the list shifts and the teacher loses their place.
If you need to add or remove items, either use a regular for loop (and be very careful with the index), or make your changes after the foreach loop finishes.
Key Takeaways
- A foreach loop goes through each item in a list, one at a time.
- You don't need a counter variable — the loop handles moving to the next item automatically.
- The loop ends when there are no more items in the list (so no risk of infinite loops!).
- Never add or remove items from the list while a foreach loop is running — it can skip items, repeat items, or cause errors.
- Use foreach when you want to do the same thing to every item in a collection.
- In pseudocode:
FOR EACH item IN list ... END FOR EACH