Java Do/While Loop

Welcome to The Coding College! In this tutorial, we’ll explore the do/while loop in Java. This loop is a variant of the while loop, but it guarantees that the code inside the loop runs at least once.

What is a Do/While Loop?

The do/while loop is a control structure that executes a block of code once and then repeatedly executes it as long as a specified condition evaluates to true.

Syntax

do {
    // Code to be executed
} while (condition);
  • do: Executes the block of code once, regardless of the condition.
  • condition: Evaluated after the loop body; if true, the loop runs again.

Key Characteristics

  1. At Least One Execution: The code inside the do block runs at least once because the condition is checked only after the first execution.
  2. Post-Condition Check: The loop evaluates the condition after the loop body is executed.
  3. Use Cases: Ideal for scenarios where you need the loop to execute at least once, such as validating user input.

Example 1: Basic Do/While Loop

public class DoWhileExample {
    public static void main(String[] args) {
        int i = 1;

        do {
            System.out.println("Count: " + i);
            i++;
        } while (i <= 5);
    }
}

Output:

Count: 1  
Count: 2  
Count: 3  
Count: 4  
Count: 5

Example 2: User Input Validation

import java.util.Scanner;

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

        do {
            System.out.print("Enter a number greater than 0: ");
            number = scanner.nextInt();
        } while (number <= 0);

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

Output Example:

Enter a number greater than 0: -5  
Enter a number greater than 0: 0  
Enter a number greater than 0: 7  
You entered: 7

Example 3: Summing Numbers

public class SumDoWhile {
    public static void main(String[] args) {
        int sum = 0, i = 1;

        do {
            sum += i; // Add i to sum
            i++;
        } while (i <= 10);

        System.out.println("Sum of numbers from 1 to 10: " + sum);
    }
}

Output:

Sum of numbers from 1 to 10: 55

Example 4: Infinite Do/While Loop

public class InfiniteDoWhile {
    public static void main(String[] args) {
        int i = 1;

        do {
            System.out.println("Iteration: " + i);
            i++;
            if (i > 5) {
                break; // Exit the loop when i is greater than 5
            }
        } while (true);
    }
}

Output:

Iteration: 1  
Iteration: 2  
Iteration: 3  
Iteration: 4  
Iteration: 5

Example 5: Nested Do/While Loops

public class NestedDoWhile {
    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);
    }
}

Output:

i = 1, j = 1  
i = 1, j = 2  
i = 1, j = 3  
i = 2, j = 1  
i = 2, j = 2  
i = 2, j = 3  
i = 3, j = 1  
i = 3, j = 2  
i = 3, j = 3

Differences Between While and Do/While

AspectWhile LoopDo/While Loop
Condition CheckBefore executing the loop bodyAfter executing the loop body
Minimum ExecutionMay not execute if condition is falseExecutes at least once
Use CaseWhen the condition may initially be falseWhen the loop must execute at least once

Practice Problems

  1. Write a program using a do/while loop to print all odd numbers between 1 and 50.
  2. Create a do/while loop that continues asking the user to guess a random number until they get it right.
  3. Implement a do/while loop to calculate the factorial of a given number.

Conclusion

The do/while loop is a great choice when you need to ensure that the loop body executes at least once. With its post-condition check, it offers flexibility for various programming scenarios.

For more Java tutorials and examples, visit The Coding College. Keep learning and coding! 🚀

Leave a Comment