Loop Control Variables and Counting Patterns
What you'll learn: How to use and manipulate variables that control loop execution and implement common counting strategies.
The Core Idea
A loop control variable is a variable that determines when a loop starts, continues, or stops. Think of it like a pedometer counting your steps during a walk—it tracks progress and tells you when you've reached your goal. The most common pattern is incrementing (counting up) or decrementing (counting down) this variable with each loop iteration.
Basic Counting Patterns
Counting Up (Incrementing)
int count = 0;
while (count < 5) {
// Loop body executes 5 times
count++; // Increment after each iteration
}
// count is now 5
This pattern starts at 0 and counts up to (but not including) 5.
Counting Down (Decrementing)
int countdown = 5;
while (countdown > 0) {
// Loop body executes 5 times
countdown--; // Decrement after each iteration
}
// countdown is now 0
This pattern starts at 5 and counts down to 1 (stops when reaching 0).
Counting by Steps
int evens = 0;
while (evens < 10) {
// Processes only even numbers: 0, 2, 4, 6, 8
evens += 2; // Increment by 2 each time
}
You can increment or decrement by any value to skip numbers or create custom patterns.
Typical Idioms
- Off-by-one awareness:
count < 5runs 5 times (0–4);count <= 5runs 6 times (0–5) - Initialize before the loop: Always set your control variable's starting value
- Modify inside the loop: Update the variable so the condition eventually becomes false
Key Takeaway: Loop control variables track iteration progress using increment (++), decrement (--), or compound assignments (+=, -=) to count through ranges and control when loops terminate.