Introduce Java For Loop and give examples
The for
loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. It is commonly used when the number of iterations is known beforehand. The for
loop consists of three main parts: initialization, condition, and increment/decrement.
for (initialization; condition; update) {
// Code to be executed in each iteration
}
true
, the loop body is executed. If it evaluates to false
, the loop terminates.Here’s a simple example that prints the numbers from 1 to 5:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
In this example, we will use a for
loop to iterate over an array of integers and print each element:
public class ArrayForLoop {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
You can also nest for
loops. Here’s an example that prints a multiplication table:
public class NestedForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + "\t");
}
System.out.println(); // Move to the next line after each row
}
}
}
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
You can also use a for
loop to count downwards. Here’s an example that counts down from 5 to 1:
public class Countdown {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
}
}
Output:
5
4
3
2
1
The for
loop is a powerful and flexible control structure in Java that allows for efficient iteration over a range of values, arrays, or collections. By understanding its syntax and structure, you can effectively use it in various programming scenarios.