do-while loop in Java programming Hands on coding

 Do while loop in Java;


Syntax:

 

  • Its body will be executing until the given condition becomes true.


Example 1:

 class Easy   
 {   
   public static void main(String[] args)   
   {   
    int x=1;   
   do   
    {   
    System.out.println(x);   
    x++;   
    }   
   while(x<10);   
   }   
 }   
 / ### Output ###   
 1 2 3 4 5 6 7 8 9 /   


Explaination:

In the above example the body of while will execute again and again as long as variable x is less than 10.


Example 2: Find factorial of any number

 //factorial of 5=1x2x3x4x5   
 //factorial of 6=1x2x3x4x5x6   
 //factorial of N=1x2x3x....xN   
 import java.util.Scanner;   
 class Easy   
 {   
   public static void main(String[] args)   
   {   
    Scanner in=new Scanner(System.in);   
    int no, f=1, i=1;   
    System.out.println("Enter any number");   
    no=in.nextInt();   
    do   
    {   
     f=f*i;   
     i++;   
    }   
    while(i<=no);   
    System.out.println("The factorial of 
                        "+no+" is "+f);   
   }   
 }   
 / ### Output ###
 Enter any number 6 
 The factorial of 6 is 720 /    



Difference between while and do while loop;

  • The difference between while loop and do while is that in the case of while loop if the condition is false then its body will not execute but in the case of do while loop its body will execute atleast one time either condition is true or false.
  • While loop can be called as entry control loop and do while loop is a exit control loop.

For Videos Join Our Youtube Channel: Join Now

Thank you!