For Loops
By the end of this lesson, you'll be able to:
- Write a classic for loop with initializer, condition, and increment
- Trace through a for loop step by step
- Use a for loop to iterate a fixed number of times
Prerequisites: "Why Loops Exist"
The three parts
for (Integer i = 0; i < 5; i++) {
System.debug('Iteration number ' + i);
}
Integer i = 0— runs once, before the loop starts.i < 5— checked before every pass; the loop stops the moment this isfalse.i++— runs after every pass, right before the condition is checked again.
This prints 0 through 4 — five iterations, not six, because i < 5 becomes false once i reaches 5.
A real business example: Retail
Integer storeCount = 12;
for (Integer storeNumber = 1; storeNumber <= storeCount; storeNumber++) {
System.debug('Generating end-of-day report for store #' + storeNumber);
}
Whenever you know exactly how many times something needs to happen — here, once per store — a classic for loop is the clearest way to express it.
Common mistakes
- Off-by-one errors.
i <= 5loops 6 times (0 through 5);i < 5loops 5 times (0 through 4). Always double-check which one you actually mean. - Forgetting the increment. Without
i++, the condition never changes and the loop never ends — Apex will eventually hit a governor limit and throw an error rather than freeze forever, but it's still a bug worth avoiding.
Counting down instead of up
for (Integer i = 5; i > 0; i--) {
System.debug(i);
}
System.debug('Liftoff!');
A for loop is not limited to counting up by one — the increment step can be any expression, including a decrement, to count down instead.
Exercise
Write a for loop that debugs the numbers 1 through 10 (inclusive).
Show hint
Start i at 1 and use <= 10 as the condition.
For Loops Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
The classic for loop packs a counter's start, its stopping condition, and how it changes each pass into one line — the most explicit and controllable loop shape in Apex.