Do While Loop in Java


The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.The do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.

  • The first body of the loop is executed.
  • The condition check to true, the body of the loop inside the do statement is executed again.
  • The condition is check again.
  • This process continues until the condition is false.
  • When the condition to false, the loop stops.

Syntax:
   do
   {
        // body of loop;
        // Increment (or) Decrement;
   }  while(Condition) ;

This Java program prompts the user to input a number and then prints out all the even integers from 2 up to that number using a do-while loop. Here is a breakdown of the code:

  • The program starts by importing the Scanner class to allow user input.
  • The class is defined as do_while and the main method is declared.
  • The program prompts the user to enter a limit and waits for the user to input a number.
  • The input number is stored in the variable n.
  • The variable i is initialized to 2.
  • The do-while loop starts with the code block between do and while.
  • Inside the do-while loop, the program prints out the value of i using the println method.
  • The value of i is then incremented by 2 using the i=i+2 shorthand notation.
  • The loop continues to run until the condition i<=n is no longer true.
  • Once the loop is finished, the program terminates.

This program is a simple example of how to use a do-while loop in Java to iterate over a range of numbers. In this case, it is used to print out all even numbers between 2 and the user-specified limit. The do-while loop is used here because we want to ensure that at least one iteration of the loop is executed even if the condition is false, so that we can output the first even number (which is 2).

Source Code

import java.util.Scanner;
 
public class do_while {
    public static void main(String args[])
    {
        System.out.println("Enter The Limit : ");
        Scanner in =new Scanner(System.in);
        int n=in.nextInt();
        int i=2;
        do {
            System.out.println(i);
            i=i+2;
        }while (i<=n);
    }
}
 

Output

Enter The Limit :
20
 
2
4
6
8
10
12
14
16
18
20
To download raw file Click Here

Basic Programs