Introduction
-
In most cases, for-each is used instead of a typical for loop statement. Foreach loops, unlike other for loop structures, usually don't have an explicit counter: they essentially state "do this to everything in this collection" rather than "do this x times." It prevents off-by-one problems and makes the code easier to read. An Iterator is frequently used as a traversal mechanism in object-oriented languages, even if implicit. You can explore more about different types of loops.
- The for-each loop is used to quickly access items of an array without having to do initialization, testing, or increment/decrement operations. Foreach loops work by doing something for each element instead of doing something n times.
Steps
- For using for each loop, we need a loop to iterate through.
- Write the syntax for the for each loop for the programming language.
- Initialize a variable and reference it to the object which is neet to iterate.
Pseudo Code
array a[] = [elements]
n = size(a)
for each i in a from 0 to n-1:
print a[i]
Foreach loop in Java
int[] arr ={1,2,3,4,5,6,7,8,9,0};
// for each loop
for (int num : arr)
{
System.out.println(num);
}
Output
1
2
3
4
5
6
7
8
9
0
Know more about What are Loops in Java and Rabin Karp Algorithm
Foreach loop in C++
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,0};
// Printing elements of an array using
// foreach loop
for (int num : arr)
cout << num << endl;
}
Output
1
2
3
4
5
6
7
8
9
0