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);
}
for (Integer i = 0; i < 5; i++) {— three parts, separated by;:Integer i = 0runs once, before the loop starts;i < 5is checked before every pass, and the loop stops the moment it'sfalse;i++runs after every pass, right before the condition is checked again.System.debug('Iteration number ' + i);— runs once per pass, withiholding a different value each time.}— closes the loop.
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);
}
Integer storeCount = 12;— the number of stores.- (blank line)
for (Integer storeNumber = 1; storeNumber <= storeCount; storeNumber++) {— starts at1(not0, since stores are naturally numbered from 1) and runs throughstoreCountinclusive, thanks to<=.System.debug('Generating end-of-day report for store #' + storeNumber);— runs once per store.}— closes the loop.
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!');
for (Integer i = 5; i > 0; i--) {— starts at5, keeps going whilei > 0, andi--decrements by one each pass instead of counting up.System.debug(i);— logs5,4,3,2, then1.}— closes the loop; it stops onceireaches0.System.debug('Liftoff!');— runs once, after the loop finishes.
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
Leaderboard
- 1. Monde Masiza 1/1
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.