Do while loop in Java.

Do while loop in Java

 
  • It's body will execute until the given condition is true.
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
*/
In the above example the body of while will execute again and again as long as variable x is less than 10.

//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 it's body will not execute but in the case of do while loop it's body will execute atleast one time either condition true or false.
  • While loop is a entry control loop and do while loop is a exit control loop.
Next Post Previous Post
No Comment
Add Comment
comment url