Example
Display the numbers from 0 to 4.
for (int i = 0; i < 5; i ++) {
System.out .println(i );
}
|
Definition and Usage
The for loop iterates through a block of code repeatedly for a specified number of times.
Based on the provided example:
- The first statement initializes a variable before the loop commences (int i = 0).
- Statement 2 establishes the condition for the loop to execute (i must be less than 5). If the condition is true, the loop repeats; if false, the loop terminates.
- Statement 3 increments a value (i++) after each execution of the code block within the loop.
More Examples
Additionally, there exists a “for-each” loop, primarily employed for traversing elements within an array:
The subsequent example demonstrates outputting all elements within the “cars” array using a “for-each” loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars ) {
System.out .println(i );
}
|