The do while loop

The do while loop is just similar to while loop, the only difference is, it is an exit controlled loop. In the do while loop condition is checked after entering into the loop body that means loop body will be executed at least once.

Syntax

do {
    // Loop body
} while(<codition>);

Simple example

In this example, we are printing a number from 0 to 9 with prefix “Item”. So it will print something like – Item 0, Item 1, Item 2… Item 9

public class SimpleExample {
    
    public static void main(String[] args) {

        int i = 0;

        do {

            System.out.println("Item " + i);
            i++;

        } while (i < 10);

    }

}

Points to note

  1. Do while loop is an exit controlled loop, means the condition is checked after entering into the loop body.
  2. Condition is evaluated every time and if it evaluated as true then control enters into loop body.
  3. The loop terminates when the condition is evaluated as false.
  4. Every time we need to increase/decrease the value of the condition variable.

Flow diagram

Natural numbers example

This is an example program that demonstrates how to use do while loop. In this program, we are printing all the natural numbers up to N.

Natural numbers are numbers that are common and clearly in nature. As such, it is a whole, nonnegative number.

import java.util.Scanner;

public class PrintNaturalNumbers {
    
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Take number from user
        System.out.print("Enter any number : ");
        int num = scanner.nextInt();

        System.out.println("\nNatural numbers from 1 to " + num);

        int i = 1;

        do {

            System.out.print(i + " ");
            i++;

        } while (i <= num);

    }

}