For Loops
Learn the most versatile loop in C++ for counting, iterating, and repeating operations
Master the for loop - the most common loop structure for counting, iterating, and repeating operations a specific number of times.
A Simple Example
#include <iostream>
int main() {
// Print numbers 1 to 5
for (int i{1}; i <= 5; i++) {
std::cout << "Iteration " << i << "\n";
}
// Countdown from 10 to 1
for (int countdown{10}; countdown >= 1; countdown--) {
std::cout << countdown << " ";
}
std::cout << "\n";
// Count by twos
for (int even{0}; even <= 10; even += 2) {
std::cout << even << " "; // 0 2 4 6 8 10
}
std::cout << "\n";
return 0;
}
Breaking It Down
For Loop Structure: for (init; condition; update)
-
Initialization:
int i{0}- runs once at the start, declares and sets the loop counter -
Condition:
i < 5- checked before each iteration, continues while true -
Update:
i++- runs after each iteration, typically increments the counter - Remember: All three parts are optional, but the semicolons are required
Common Loop Patterns
-
Count up:
for (int i{0}; i < 10; i++)- most common pattern -
Count down:
for (int i{10}; i > 0; i--)- useful for reverse iteration -
Skip values:
for (int i{0}; i < 10; i += 2)- increment by any amount - Remember: The update expression can be any valid C++ statement
Loop Variable Scope
- Variables declared in the init section exist only inside the loop
-
Example:
for (int i{0}; i < 5; i++)- i is only valid within the loop body - After the loop ends, the variable is destroyed and cannot be accessed
- Remember: This is good practice - it keeps variables limited to where they are needed
When to Use For vs While Loops
- Use for loops when you know the number of iterations in advance
- Use for loops when counting or iterating over a range
- Use while loops when waiting for a condition or unknown iteration count
- Remember: Any for loop can be converted to a while loop, but for is clearer for counting
Why This Matters
- For loops are the workhorses of programming. Processing arrays, generating sequences, iterating over collections - these tasks appear in almost every program.
- The for loop packages initialization, condition checking, and increment into one compact, readable line. This makes your intent clear and reduces errors.
Critical Insight
Any for loop can be written as a while loop, but not the other way around! For loops are just more convenient when counting:
// For loop version - compact and clear
for (int i{0}; i < 5; i++) {
std::cout << i << "\n";
}
// Equivalent while loop - more verbose
int i{0};
while (i < 5) {
std::cout << i << "\n";
i++;
}
Choose for loops when: You are counting, iterating a known number of times, or working with ranges.
Choose while loops when: You are waiting for user input, processing until a sentinel value, or do not know iteration count upfront.
Best Practices
Use meaningful counter names: Instead of i, use descriptive names like dayIndex or studentNum when it makes the code clearer.
Prefer < over <= for array bounds: Use for (int i{0}; i < 10; i++) to iterate 10 times. This matches how arrays are indexed (0 to 9).
Keep loop bodies simple: If your loop body is long or complex, consider extracting it into a separate function for better readability.
Declare counter in the init section: Use for (int i{0}; ...) instead of declaring i before the loop. This limits the variable scope.
Common Mistakes
Off-by-One Errors: Using i <= 10 instead of i < 10 makes the loop run 11 times instead of 10. Always double-check your condition.
Modifying Loop Variable Inside Loop: Changing i inside the loop body can cause confusion and bugs. Let the update expression handle it.
Infinite Loops from Wrong Increment: Forgetting to increment or using the wrong operator like i-- when counting up creates infinite loops.
Semicolon After For Statement: for (int i{0}; i < 5; i++); with a semicolon creates an empty loop that does nothing. The intended body becomes separate code.
Debug Challenge
This for loop should print numbers 0 to 4, but it has a bug. Click the highlighted line to fix it:
Quick Quiz
- How many times does this loop execute?
for (int i{0}; i < 10; i++)
- What is the final value printed by this code?
for (int i{2}; i < 10; i += 2) {
std::cout << i << " ";
}
- Which loop is best for processing exactly 100 items?
Practice Playground
Time to try out what you just learned! Play with the example code below, experiment by making changes and running the code to deepen your understanding.
Output:
Error:
Lesson Progress
- Fix This Code
- Quick Quiz
- Practice Playground - run once