Curriculum
In Java, the for loop is a control flow statement that allows you to execute a block of code repeatedly for a fixed number of times. The syntax of a for loop is as follows:
for (initialization; condition; update) {
// code to be executed repeatedly
}
The initialization statement is executed once at the beginning of the loop, and is typically used to initialize a loop variable. The condition is an expression that is tested at the beginning of each iteration of the loop. If the condition is true, the code inside the loop is executed. The update statement is executed at the end of each iteration of the loop, and is typically used to update the loop variable.
Here’s an example of a simple for loop:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
In this example, the for loop iterates 5 times. The loop variable i is initialized to 0, and during each iteration, the value of i is printed to the console, and then i is incremented by 1. The loop will terminate when i is equal to 5.
Another use of a for loop is to iterate over an array or collection of data. Here’s an example:
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
In this example, the for loop iterates over the elements of the numbers array. The loop variable i is used as an index to access each element of the array, and during each iteration, the value of the current element is printed to the console.
It’s important to make sure that the condition used in a for loop eventually becomes false, or the loop will continue to execute indefinitely, leading to an infinite loop. Infinite loops can cause your program to crash or become unresponsive, so it’s important to use conditions that will eventually become false.