How to use for each loop in Java
The for each loop is designed to cycle through a collection of objects in sequential fashion from beginning to end. The collection of objects can be an array.
Syntax:
for(type iteration-variable: collection)
{
Statement block;
}
Here type is same as the data type used in the array/collection. The iteration variable collect data from each element in the array.
for each Example Java Program
/* Java program to take the sum of first 10 digits using
for each loop */
public class ForEachLoopExample {
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) sum += x;
System.out.println("Sum is: " + sum);
}
}
Output:
Sum is: 55
Note: There is no keyword named foreach to perform the foreach style of loop operation in Java.
No comments :
Post a Comment