Loop



Loop is a specific block executed continuously until the given condition is false.



Types of loop statement



  1. while loop
  2. do while loop
  3. for loop







1. while-loop



while loop initially check the condition.It will iterate the statement when the condition is true.when the condition is false the loop will be exit.We don't know the number of iteration in while loop.



while(condition)
{
   #state;
}







Example
public class Main
{
     public static void main(String[] args) 
     {
          int n=0;
          while(n<5)
          {
                System.out.println(n);
                n++;
          }
     }
}


Output



0
1
2
3
4









2. do while-loop



"do while" loop check the condition at the end of the loop. It will iterate the statement when the condition is true.when the condition is false the loop will be exit. if condition is true or false , The loop must run one time.



 do{

   #statement;

} while(condition);







Example
public class Main
{
      public static void main(String[] args) 
      {
           int n=0;
           do{
                System.out.println(n);
                n++;
           }while(n<5);
      }
}


Output




0
1
2
3
4









3. for-loop



for loop initially check the condition. It will iterate the statement when the condition is true.when the condition is false the loop will be exit. In for loop the number of iteration is you already know.



 for(intial;condition;increament/decrement)
 {
     #statement;
 }







Example-1
public class Main
{
      public static void main(String[] args) 
      {
           for(int i=0;i<5;i++)
           {
                System.out.println(i);
           }
      }
}


Output



0
1
2
3
4