Author
Loops in Java are used to repeat a block of code multiple times. They help automate repetitive tasks, reduce errors, and make your code efficient.
A loop executes a block of code repeatedly until a condition becomes false.
Types of loops in Java:

Used when you know how many times you want to repeat a block.
for (initialization; condition; update) {
// code to execute
}
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Output:
1
2
3
4
5
while (condition) {
// code to execute
}
int total = 0;
int num = 1;
while (total < 50) {
total += num;
num++;
}
System.out.println("Total: " + total);
Output:
Total: 55
do {
// code to execute
} while (condition);
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = sc.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);
sc.close();
for (type var : arrayOrCollection) {
// code
}
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
Output:
10
20
30
40
You can place one loop inside another. Useful for patterns, matrices, etc.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
* * *
* * *
* * *
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println("Factorial of " + n + " is " + factorial);
sc.close();
}
}
Output Example:
Enter a number: 5
Factorial of 5 is 120