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) ;

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