A while loop works well when you count by hand: you set up a counter, check a condition, and remember to update the counter yourself. A for loop packages all three of those steps into a single line, which makes counting loops shorter and harder to get wrong.
A for loop has three parts inside the parentheses, separated by semicolons:
for (Integer i = 0; i < 5; i++) {
System.debug('i is ' + i);
}
Integer i = 0) runs one time before the loop starts.i < 5) is checked before every pass. When it is false, the loop stops.i++) runs at the end of every pass.This loop prints 0, 1, 2, 3, and 4. The counter starts at 0, the body runs while i is less than 5, and i grows by one each time.
Because all three parts live in one place, a for loop is easy to adjust. You can start somewhere else, stop somewhere else, or step by a different amount:
// Count 1 through 10
for (Integer i = 1; i <= 10; i++) {
System.debug(i);
}
// Count down from 5 to 1
for (Integer i = 5; i >= 1; i--) {
System.debug(i);
}
// Step by two: 0, 2, 4, 6
for (Integer i = 0; i <= 6; i += 2) {
System.debug(i);
}
A for loop keeps the counter, the stopping test, and the update together, so it is easy to read and hard to forget a step. When you know how many times you need to repeat, a for loop is usually the clearest choice.