Overview
For loops are used to execute a block of code repeatedly for a specific number of times. They are ideal when you know in advance how many iterations you need.Basic Syntax
Basic Incrementing Loop
The most common form of a for loop increments a counter:The loop variable can be declared with
int, var, or final. Use int when you want to be explicit about the type.Decrementing Loop
You can decrement the counter to loop backwards:Custom Increment Values
You can modify the increment step to skip values:Modifying Loop Variable Inside Body
You can alter the loop variable within the loop body:Complete Example
For Loop Components
1
Initialization
Executed once before the loop starts. Typically used to declare and initialize the loop counter.
2
Condition
Checked before each iteration. The loop continues as long as this evaluates to
true.3
Increment
Executed after each iteration. Usually increments or decrements the loop counter.
4
Body
The code block that executes on each iteration.
Common Patterns
Iterating from 0 to n-1
Iterating from 1 to n
Iterating backwards
Iterating with step size
For-in Loop
Best Practices
- Use meaningful variable names instead of just
iwhen the loop purpose isn’t obvious - Keep loop bodies simple and focused
- Consider using
for-inloops when iterating over collections - Avoid modifying the loop variable inside the loop body
- Use
breakto exit early andcontinueto skip iterations when needed