Java do-while Loop


Introduction

The do-while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. Unlike the while loop, the do-while loop guarantees that the code block is executed at least once before the condition is tested. This makes the do-while loop particularly useful for scenarios where you need to ensure that the code block executes at least once.

Table of Contents

  1. What is a do-while Loop?
  2. Syntax of do-while Loop
  3. How do-while Loop Works
  4. Simple do-while Loop Example
  5. Infinite do-while Loop
  6. do-while Loop with a Break Statement
  7. do-while Loop with a Continue Statement
  8. Nested do-while Loop
  9. Using a do-while Loop for Input Validation
  10. Conclusion

What is a do-while Loop?

A do-while loop repeatedly executes a block of code as long as the specified condition evaluates to true. The key difference from a while loop is that the condition is evaluated after the loop body, ensuring that the loop body is executed at least once.

Syntax of do-while Loop

Syntax:

do {
    // body of loop
} while (condition);
  • condition: A boolean expression that is evaluated after each iteration of the loop.
  • body of loop: The block of code that is executed at least once and as long as the condition is true.

How do-while Loop Works

  1. The loop body is executed.
  2. The condition is evaluated.
  3. If the condition is true, the loop body is executed again.
  4. Steps 2 and 3 are repeated until the condition becomes false.
  5. When the condition is false, the loop terminates, and control moves to the next statement after the loop.

Simple do-while Loop Example

Example:

public class SimpleDoWhileLoop {
    public static void main(String[] args) {
        int count = 1;
        do {
            System.out.println("Count: " + count);
            count++;
        } while (count <= 5);
    }
}

Explanation: This loop prints the numbers from 1 to 5. The body of the loop is executed first, and then the condition count <= 5 is checked. Since the condition is true, the loop continues to execute until count exceeds 5.

Infinite do-while Loop

An infinite loop occurs when the condition always evaluates to true.

Example:

public class InfiniteDoWhileLoop {
    public static void main(String[] args) {
        do {
            System.out.println("This is an infinite loop");
        } while (true);
    }
}

Explanation: This loop will print "This is an infinite loop" indefinitely because the condition true never changes.

do-while Loop with a Break Statement

The break statement can be used to exit the loop prematurely.

Example:

public class DoWhileWithBreak {
    public static void main(String[] args) {
        int count = 1;
        do {
            if (count == 5) {
                break;
            }
            System.out.println("Count: " + count);
            count++;
        } while (count <= 10);
    }
}

Explanation: This loop prints numbers from 1 to 4. When count equals 5, the break statement exits the loop.

do-while Loop with a Continue Statement

The continue statement skips the current iteration and moves to the next iteration of the loop.

Example:

public class DoWhileWithContinue {
    public static void main(String[] args) {
        int count = 0;
        do {
            count++;
            if (count % 2 == 0) {
                continue;
            }
            System.out.println("Odd number: " + count);
        } while (count < 10);
    }
}

Explanation: This loop prints odd numbers from 1 to 9. The continue statement skips the even numbers.

Nested do-while Loop

A nested do-while loop is a do-while loop inside another do-while loop, useful for iterating over multidimensional structures.

Example:

public class NestedDoWhileLoop {
    public static void main(String[] args) {
        int i = 1;
        do {
            int j = 1;
            do {
                System.out.println("i: " + i + ", j: " + j);
                j++;
            } while (j <= 3);
            i++;
        } while (i <= 3);
    }
}

Explanation: This loop prints pairs of i and j values, iterating over all combinations of i and j from 1 to 3.

Using a do-while Loop for Input Validation

The do-while loop is often used for validating user input.

Example:

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number;

        do {
            System.out.print("Enter a positive number: ");
            number = scanner.nextInt();
            if (number <= 0) {
                System.out.println("Invalid input. Please try again.");
            }
        } while (number <= 0);

        System.out.println("You entered: " + number);
        scanner.close();
    }
}

Explanation: This loop repeatedly prompts the user to enter a positive number until a valid input is provided.

Conclusion

The do-while loop in Java is a powerful control flow statement for performing repeated tasks based on a condition. Unlike the while loop, the do-while loop guarantees that the code block is executed at least once. Understanding how to use the do-while loop effectively, including its variations with break and continue statements, as well as nested loops, is essential for writing robust and efficient Java programs.


Comments