The For Loop
What you'll learn: You'll discover how the for loop lets you repeat actions a specific number of times with clean, compact syntax.
Why For Loops Exist
You've already learned the while loop, which repeats as long as a condition stays true. But what if you know exactly how many times you want to repeat something? That's where the for loop shines. It bundles the loop control variable, the condition, and the update all in one line—making your code cleaner and less error-prone.
The For Loop Structure
Think of a for loop like setting a kitchen timer: you decide the starting count, when to stop, and how to count (by ones, twos, etc.). Most languages follow this pattern:
for (initialization; condition; update) {
// code to repeat
}
Initialization: Set your loop control variable (e.g., i = 0)
Condition: Keep looping while this is true (e.g., i < 10)
Update: Change the variable after each repetition (e.g., i = i + 1)
A Simple Example
Let's count from 0 to 4:
for (i = 0; i < 5; i = i + 1) {
print(i)
}
This prints: 0, 1, 2, 3, 4
The loop runs exactly 5 times. It's equivalent to a while loop, but everything's organized in one readable line instead of scattered across your code.
When to Use For vs While
Use for when you know the iteration count beforehand. Use while when you're waiting for a condition to change unpredictably.
Key Takeaway: The for loop provides compact syntax for repeating code a specific number of times by bundling initialization, condition, and update together.