Overview
The for
loop in Java is used for iterating over a set of elements or performing repetitive tasks a certain number of times. It is especially useful when you know the number of iterations in advance. The for
loop consists of three parts: initialization, condition, and update. The loop body will execute as long as the condition is true.
Syntax
javafor (initialization; condition; update) {
// Code to be executed in each iteration
}
Initialization: This part is executed only once before the loop starts. It typically initializes a loop control variable.
Condition: The loop continues executing as long as the condition is true. It is evaluated before each iteration.
Update: This part is executed after each iteration. It usually updates the loop control variable.
Example 1: Print Numbers from 1 to 5
javafor (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Explanation: In this example, the loop starts with i
initialized to 1. The loop continues as long as i
is less than or equal to 5. After each iteration, the value of i
is incremented by 1 (i++). So, the loop will print the numbers from 1 to 5.
Example 2: Calculate the Sum of First 10 Natural Numbers
javaint sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("Sum of first 10 natural numbers: " + sum);
Explanation: In this example, the loop starts with i
initialized to 1 and the sum
variable set to 0. The loop continues as long as i
is less than or equal to 10. In each iteration, the value of i
is added to the sum
. After the loop, the final value of sum
will be the sum of the first 10 natural numbers.
Example 3: Looping through an Array
javaint[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
Explanation: In this example, we have an integer array numbers
. The loop starts with i
initialized to 0, and it continues as long as i
is less than the length of the array (numbers.length
). In each iteration, the loop prints the element at the current index i
.
Example 4: Looping with Step Size
javafor (int i = 0; i < 10; i += 2) {
System.out.println(i);
}
Explanation: In this example, the loop starts with i
initialized to 0. The loop continues as long as i
is less than 10. After each iteration, the value of i
is incremented by 2 (i += 2). So, the loop will print even numbers from 0 to 8 (inclusive).
The for
loop is a powerful construct in Java that allows you to efficiently execute repetitive tasks based on a defined pattern. Understanding the syntax and proper usage of the for
loop is essential for writing effective Java programs.
0 Comments