Foreach loop in C++ by R4R Team

In C++,
There are four types of loops:
-for loop
-while loop
-do while loop
-foreach loop

Foreach loop:
-Apart from other loop this loop is special kind of functionality.
-This loop is not present in C language.
-For each loop are used to iterate the sequence or collection like vectors.

Syntax-
for_each (InputIterator first, InputIterator last, Function fn)

program:

#include< iostream>
#include< algorithm>
using namespace std;
int func(int i)
{
cout<< i< }
int main()
{
int a[5]={1,2,3,4,5};
for_each(a,a+5,func);
return 0;
}


output-

1
2
3
4
5

-In this program, we print all value of array using for_each loop and func() function.
-It actually pass each element in function 'func()' then we do whatever we want to do with array.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!