Java provides different types of loops to perform repetitive tasks.
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}
This program uses a for loop to print the iteration number from 1 to 5.
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}
}
}
This example demonstrates the use of a while loop to perform the same task as the for loop above.
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);
}
}
The do-while loop guarantees at least one iteration even if the condition is false at the start.