Java Language – 7 – Loops (for, while, do-while)

Java Fundamentals – Loops (for, while, do-while)
Introduction

Loops are essential in Java for executing a block of code repeatedly. They allow you to automate tasks, process data, and control program flow efficiently. In this guide, we’ll explore three common loop types in Java: ‘for,’ ‘while,’ and ‘do-while.’

The ‘for’ Loop

The ‘for’ loop is used when you need to repeat a specific block of code a known number of times. It is ideal for tasks where you can precisely control loop initialization, condition, and iteration:


for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}

In this example, the ‘for’ loop runs five times, and ‘i’ is used as a counter to keep track of the current iteration.

The ‘while’ Loop

The ‘while’ loop is suitable for situations where you want to execute a block of code as long as a particular condition is true. It is often used when the number of iterations is not known in advance:


int count = 0;
while (count < 5) {
    System.out.println("Count: " + count);
    count++;
}

In this example, the ‘while’ loop keeps running as long as the condition ‘count < 5’ remains true, and ‘count’ is incremented with each iteration.

The ‘do-while’ Loop

The ‘do-while’ loop is similar to the ‘while’ loop but guarantees that the block of code is executed at least once before checking the condition. This ensures that the loop body is always executed:


int num = 0;
do {
    System.out.println("Number: " + num);
    num++;
} while (num < 3);

In this case, the code block is executed at least once, and then the condition ‘num < 3’ is checked to determine if the loop should continue.

Loop Control Statements

Java provides several control statements to modify the flow of loops. These include ‘break’ and ‘continue’:


for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Exit the loop
    }
    if (i % 2 == 0) {
        continue; // Skip even numbers
    }
    System.out.println("Number: " + i);
}

‘break’ is used to exit the loop prematurely, while ‘continue’ skips the current iteration and continues with the next one.

Nested Loops

Java allows you to nest loops within each other to create complex looping structures. This is particularly useful for tasks that involve multiple dimensions or nested data structures:


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

In this nested ‘for’ loop example, we generate a multiplication table by iterating through rows and columns.

Conclusion

Loops are fundamental in Java programming for automating repetitive tasks, processing data, and controlling program flow. By understanding how to use ‘for,’ ‘while,’ and ‘do-while’ loops, as well as loop control statements, you gain the ability to efficiently manage a wide range of scenarios in your Java programs.