Day19 : Using for Each Loop

 Using For-Each Loop

Syntax : 
            for <data_type><var> : <array_name>
            {
                //Statement
            }

int [ ] arr = {10,20,30,40,50}
           
                for(int x : arr)
                {
                    System.out.println(x);
                }
    
Output : 
            10 20 30 40 50 

Advantages of for-each loop:

  1. Syntax is easy compared to regular for loop because initialization, condition, increment is automatically done by java.
  2. No chances of Loop running infinitely.
  3. No chances array index out of Bounds Exception

Drawback Or Restriction

  1. It will always traversed the array from index[0] to length[-1]
  2. It will pass through every element of the array. i.e., we cannot skip any element
  3. It can only access array data but cannot make any kind of change in it.
  4. We should use this loop for full array traversal and when we don't want to make any changes in array values.
Problem : Write a Java program to Add two number by using for - each loop and also find Average.

class AddNo
{
public static void main(String[ ] args)
{
int n = args.length;
if(n>=2)
{
System.out.println("Please Input atleast 2 number ");
System.exit(0);
}
int sum = 0;
for(String x: args)
{
sum = sum + Integer.parseInt(x);
}
System.out.println("sum is "+sum);
System.out.println("Average is "+(float)sum/n);
}
}




Comments

Popular posts from this blog

Day2 : Compiling Java Program with Examples

Day1: Introduction to Java and its feature

What does System.out.printf( "%-15s%03d\n", s1, x) do?