for Loop
In Java, the for
loop is used to repeatedly execute a block of code a certain number of times. It provides a concise and structured way to iterate over a range of values or elements in an array or collection. The basic syntax of the for
loop is as follows:
for (initialization; condition; update) {
// Code to be executed in each iteration
}
Initialization: Executes once before the loop starts. It is used to initialize the loop control variable.
Condition: Checked before each iteration. If it evaluates to true
, the loop continues; otherwise, the loop exits.
Update: Executed after each iteration. It is used to update the loop control variable.
Example:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
In this example:
int i = 1
initializes the loop control variablei
to 1.i <= 5
is the condition. As long as this condition istrue
, the loop continues.i++
is the update statement. It increments the value ofi
after each iteration.
The output of this program will be:
1
2
3
4
5
Enhanced for Loop (for-each):
In addition to the traditional for
loop, Java provides an enhanced for
loop, also known as the for-each loop. It simplifies the iteration over elements in an array or collection. The syntax is as follows:
for (element_type element_variable : array_or_collection) {
// Code to be executed for each element
}
Example using an array:
public class EnhancedForLoopExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
}
}
In this example, num
takes on the value of each element in the numbers
array in each iteration of the loop.
Nested for Loops:
You can also have nested for
loops, where one for
loop is inside another. This is often used for iterating over two-dimensional arrays or for performing nested iterations.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
This nested loop will produce the following output:
i: 1, j: 1
i: 1, j: 2
i: 2, j: 1
i: 2, j: 2
i: 3, j: 1
i: 3, j: 2
The outer loop runs three times, and for each iteration of the outer loop, the inner loop runs twice.
The for
loop is a fundamental construct for repetitive tasks in Java, and mastering its usage is essential for writing efficient and readable code.