C

Core Java tutorial for beginners

Clean • Professional

Java Loops – for, while, do-while & for-each Explained

4 minute

Loops in Java

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.


What Are Loops in Java?

A loop executes a block of code repeatedly until a condition becomes false.

Types of loops in Java:

learn code with durgesh images

 

1. for Loop

Used when you know how many times you want to repeat a block.

Syntax:

for (initialization; condition; update) {
    // code to execute
}

Example: Print 1 to 5

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Output:

1
2
3
4
5

2. while Loop

  • Used when you don’t know the exact number of iterations in advance.
  • Condition is checked before executing the block.

Syntax:

while (condition) {
    // code to execute
}

Example: Sum numbers until total < 50

int total = 0;
int num = 1;

while (total < 50) {
    total += num;
    num++;
}

System.out.println("Total: " + total);

Output:

Total: 55

3. do-while Loop

  • Executes the block at least once, then checks the condition.
  • Useful when code must run at least once regardless of condition.

Syntax:

do {
    // code to execute
} while (condition);

Example: Input validation

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();

4. for-each Loop

  • Used to iterate through arrays or collections without worrying about index.
  • Introduced in Java 5 (enhanced for loop).

Syntax:

for (type var : arrayOrCollection) {
    // code
}

Example: Iterating through an array

int[] numbers = {10, 20, 30, 40};

for (int num : numbers) {
    System.out.println(num);
}

Output:

10
20
30
40

Nested Loops

You can place one loop inside another. Useful for patterns, matrices, etc.

Example: Print 3x3 stars

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.print("* ");
    }
    System.out.println();
}

Output:

* * *
* * *
* * *

Example: Calculate Factorial Using Loops

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

 

Article 0 of 0