for Loops
A for
loop allows you to repeat blocks of code for a specified duration. You can have a block of code repeat a specific number of times or repeat until a specified condition is met. The for
loop syntax has three key components:
-
initialExpression:
This part of the loop syntax initializes the variable that will be used to determine how many times the loop is executed. TheinitialExpression
part is only executed once. -
condition:
This is the condition for determining whether or not to execute the code in the body of the loop (similar to anif
statement condition). Ifcondition
evaluates totrue
, the body of thefor
loop executes. -
updateExpression:
This part of the expression updates the variable initialized in theinitialExpression
. Thecondition
is then evaluated again to see if the condition is stilltrue
with the updated value of the variable.
Examples
Performing a Set Number of Actions
for(int count = 0; count < 5; count++) {
System.out.println(count);
}
Output:
0
1
2
3
4
Traversing an Array
A for
loop can be used to traverse arrays and ArrayList
s.
int[] numbers = { 1, 2, 3, 4 };
for(int index =0; index < numbers.length; index++) {
System.out.println(numbers[index]);
}
Output:
1
2
3
4
Syntax
for (initialExpression; condition; updateExpression) {
// body of code
}