do-while Loop

Java do-while Loop: A Detailed Tutorial

The do-while loop is another fundamental control structure in Java that allows you to execute a block of code repeatedly. Unlike the while loop, which checks the condition before executing the loop body, the do-while loop checks the condition after executing the loop body. This ensures that the code inside the loop is executed at least once, even if the condition is false initially.


1. What is a do-while Loop?

A do-while loop in Java is a control flow statement that repeatedly executes a block of code at least once and then continues executing the loop as long as the specified condition evaluates to true. The main difference between a while loop and a do-while loop is that the do-while loop checks its condition after the loop body has executed.

Basic Syntax:

do {
    // Code to be executed
} while (condition);
  • Loop Body: The code inside the do block is executed first.

  • Condition: The condition is checked after the loop body has executed. If the condition is true, the loop repeats; if it is false, the loop terminates.


2. Basic Example of a do-while Loop

Let's start with a simple example where we print the numbers from 1 to 5 using a do-while loop:

int i = 1;

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

Explanation:

  • Initialization: int i = 1; - The loop starts with i equal to 1.

  • Loop Body: The code inside the do block is executed, printing the value of i.

  • Condition: i <= 5; - The loop will continue as long as i is less than or equal to 5.

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

3. Key Features of the do-while Loop

  • Guaranteed Execution: The loop body is executed at least once, even if the condition is false initially. This is the main feature that distinguishes the do-while loop from the while loop.

  • Condition Checked After Execution: The condition is evaluated after the loop body has executed, ensuring that the loop body runs before the condition is checked.


4. Practical Examples of do-while Loop

4.1 User Input Validation

The do-while loop is commonly used for input validation, where you want to prompt the user for input at least once and repeat the prompt if the input is invalid.

Example:

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
int number;

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

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

Explanation:

  • Loop Body: The user is prompted to enter a positive number.

  • Condition: The loop continues until the user enters a positive number.

Output Example:

Enter a positive number: -5
Enter a positive number: 0
Enter a positive number: 3
You entered: 3

In this example, the loop will keep prompting the user until a positive number is entered.

4.2 Summing Numbers

You can use a do-while loop to sum a series of numbers. Here's an example that calculates the sum of the first 10 positive integers:

Example:

int sum = 0;
int i = 1;

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

System.out.println("The sum is: " + sum);

Explanation:

  • Loop Body: The current value of i is added to the sum.

  • Condition: The loop continues as long as i is less than or equal to 10.

Output:

The sum is: 55

5. Infinite do-while Loop

A do-while loop can become infinite if the condition never evaluates to false. This can be intentional in scenarios like server applications or event listeners that need to run indefinitely.

Example:

do {
    System.out.println("This is an infinite loop.");
} while (true);

In this example, the loop will run indefinitely because the condition true is always satisfied.


6. Controlling the Loop with break and continue

You can control the flow of the do-while loop using the break and continue statements.

6.1 Using break

The break statement exits the loop immediately, regardless of the loop's condition.

Example:

int i = 1;

do {
    if (i == 3) {
        break;  // Exit the loop when i is 3
    }
    System.out.println("i: " + i);
    i++;
} while (i <= 5);

Output:

i: 1
i: 2

In this example, the loop terminates when i equals 3, so only the values 1 and 2 are printed.

6.2 Using continue

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

Example:

int i = 1;

do {
    if (i == 3) {
        i++;  // Increment i before continue to avoid an infinite loop
        continue;  // Skip the iteration when i is 3
    }
    System.out.println("i: " + i);
    i++;
} while (i <= 5);

Output:

i: 1
i: 2
i: 4
i: 5

In this example, when i equals 3, the continue statement skips that iteration, so 3 is not printed.


7. Nested do-while Loop

Just like the for and while loops, you can nest do-while loops, which means placing one do-while loop inside another. This is useful for handling multi-dimensional data or performing repeated operations within each iteration of an outer loop.

7.1 Example of a Nested do-while Loop

Let's create a nested do-while loop that prints a multiplication table from 1 to 3.

Example:

int i = 1;

do {
    int j = 1;
    do {
        System.out.println(i + " * " + j + " = " + (i * j));
        j++;
    } while (j <= 3);
    i++;
    System.out.println();  // Print a blank line after each table row
} while (i <= 3);

Explanation:

  • Outer Loop: Controls the rows of the multiplication table (numbers 1 to 3).

  • Inner Loop: Controls the columns of the table, multiplying i by j.

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

In this example, the outer loop iterates through the numbers 1 to 3, while the inner loop multiplies each number by 1, 2, and 3.


Conclusion

The do-while loop is a useful control structure in Java when you need to ensure that a block of code is executed at least once. Whether you're using it for input validation, summing numbers, or handling complex tasks with nested loops, mastering the do-while loop is essential for effective Java programming.

For more Java tutorials and resources, visit codeswithpankaj.com.

Last updated