Foreach loop is another loop which was introduced in C++ 11. The advantage of foreach loop over other loops is that, it can access elements of an array quickly without performing initialization, testing and increment/decrement, the code becomes more readable and there are less programming errors. The working of foreach loops is to do something for every element in an array rather than doing something n times.
The keyword used for foreach loop is “for” in C++.
Program to demonstrate use of foreach loop is as follows:-
// C++ program to demonstrate use of foreach
#include <iostream>
using namespace std;
int main()
{
int arr[] = {50, 100, 90, 40};
for (int i : arr) // Printing elements of an array using foreach loop
cout << i << endl;
}
Output:
50
100
90
40
0 Comment(s)