Loops
Dashboard
Topic 6/30
Home › Loops

🔄 Loops

Master iterative execution in Java using for, while, do-while loops, and understand loop control statements.

For Loop

The for loop is used when the number of iterations is known. It has initialization, condition, and increment/decrement parts.

FibonacciSeries.java Java
public class FibonacciSeries {
    public static void main(String[] args) {
        int n = 10, a = 0, b = 1;
        System.out.print(a + " " + b + " ");
        
        for (int i = 2; i < n; i++) {
            int next = a + b;
            System.out.print(next + " ");
            a = b;
            b = next;
        }
    }
}

Nested Loops

You can put loops inside other loops. Useful for matrices and patterns.

PatternPrinting.java Java
public class PatternPrinting {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}
MultiplicationTable.java Java
public class MultiplicationTable {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.println(i + " x " + j + " = " + (i * j));
            }
            System.out.println("---");
        }
    }
}

While Loop

The while loop executes as long as a condition remains true. It's best used when the number of iterations is unknown.

PrimeNumbers.java Java
public class PrimeNumbers {
    public static void main(String[] args) {
        int num = 29;
        boolean isPrime = true;
        int i = 2;
        
        while (i <= num / 2) {
            if (num % i == 0) {
                isPrime = false;
                break; // exit loop immediately
            }
            i++;
        }
        
        System.out.println(num + (isPrime ? " is Prime" : " is not Prime"));
    }
}

Do-While Loop

The do-while loop executes the block at least once before checking the condition.

DigitSum.java Java
public class DigitSum {
    public static void main(String[] args) {
        int number = 12345;
        int sum = 0;
        
        do {
            sum += number % 10;
            number /= 10;
        } while (number > 0);
        
        System.out.println("Sum of digits: " + sum);
    }
}
Infinite Loops: Forgetting to update the loop variable (like number /= 10) will result in an infinite loop, freezing your program!