Looping

Loops in Java are used to execute a block of code repeatedly as long as a specified condition is met. Java provides several types of loops to cater to different looping requirements. Here are the main types of loops in Java, along with explanations and examples:

1. for Loop:

The for loop is used when you know in advance how many times you want to loop.

Syntax:

for (initialization; condition; update) {
    // Code to be executed repeatedly
}

Example:

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Iteration " + i);
        }
    }
}

Explanation:

  • The for loop here runs from i = 1 to i = 5. In each iteration, it prints the message "Iteration i" to the console.

2. while Loop:

The while loop is used when the number of iterations is not known beforehand, but the loop continues as long as a specified condition is true.

Syntax:

while (condition) {
    // Code to be executed repeatedly
}

Example:

public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Iteration " + i);
            i++;
        }
    }
}

Explanation:

  • The while loop here starts with i = 1. It continues to iterate and print the message as long as i is less than or equal to 5.

3. do-while Loop:

The do-while loop is similar to the while loop, but the condition is evaluated after the loop body, ensuring that the loop executes at least once.

Syntax:

do {
    // Code to be executed repeatedly
} while (condition);

Example:

public class DoWhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("Iteration " + i);
            i++;
        } while (i <= 5);
    }
}

Explanation:

  • In the do-while loop, the message is printed and i is incremented inside the loop. The loop will run at least once even if the condition is false initially.

These are the main types of loops in Java. They enable you to repeat code execution based on specific conditions, allowing for efficient and controlled iterations in your programs.

Last updated