For each loop in Java programming Hands on Coding

  For each loop in Java


Syntax: 


  • It is a special type of loop which is used mostly with array.
  • It stores each element of array in a variable and executes the body of loop.
  • It starts with for keyword like a normal for loop.

Example 1:Program with foreach loop

 class Easy  
 {  
  public static void main(String[] args)   
  {  
  //array declaration  
  int ar[]={10,50,60,80,90};  
  for (int element:ar)   
   System.out.print(element+" ");      
  }  
 } 
 
 /*  
 ### Output ###  
 10 50 60 80 90  
 */  


Example 2:Same program with for loop

 class Easy  
 {  
  public static void main(String[] args)   
  {  
  //array declaration  
  int ar[]={10,50,60,80,90};  
  for (int i = 0; i <ar.length; i++)   
   System.out.print(ar[i]+" ");      
  }  
 }  
 
 /*  
 ### Output ###  
 10 50 60 80 90  
 */  


Hope This is useful for you. Visit our channel for job updates- Youtube

Post a Comment

0 Comments