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:
- Syntax is easy compared to regular for loop because initialization, condition, increment is automatically done by java.
- No chances of Loop running infinitely.
- No chances array index out of Bounds Exception
Drawback Or Restriction
- It will always traversed the array from index[0] to length[-1]
- It will pass through every element of the array. i.e., we cannot skip any element
- It can only access array data but cannot make any kind of change in it.
- 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