Java Program using For_each loop…

For_each loop

This loop is specifically designed for collection like array.
Syntax:
for(var : Collection)
{
Statements;
}
Example:
class ForEach
{
  public static void main(String args [])
  {
    int nums[]={1,2,3,4,5,6,7,8,9,10};
    int sum=0;
    for(int x:nums)
    {
      System.out.println(“Value is = ” + x);
      sum=sum+x;
    }
      System.out.println(“summation is = ” + sum);
  }
}
Output:
D:javapracch4and5>java ForEach
Value is = 1
Value is = 2
Value is = 3
Value is = 4
Value is = 5
Value is = 6
Value is = 7
Value is = 8
Value is = 9
Value is = 10
summation is = 55

Add Comment