while loop in Java programming Hands on coding

While loop in Java;


Syntax;

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


Example 1;

 class Easy   
 {   
   public static void main(String[] args)   
   {   
    int x=1;   
    while(x<10)   
    {   
     System.out.println(x); x++;   
     }   
   }   
 }   
/ ### 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 variablex 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();   
   while(i<=no)   
    {   
     f=f*i;   
     i++;   
    }   
   System.out.println("The factorial of "+no+" is "+f);   
  }   
 }   
 / ### Output ### Enter any number 6 The factorial of 6 is 720 /   


For Videos Join Our Youtube Channel: Join Now

Thank you!