Please login


Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

For each loop in C++

for_each loop in C++

  • As the name suggests you need to print each element in the set
  • Ordinary loops must have the condition increments/decrements actions were as for each loop need not have any conditions and increments

definition of the for_each loop: It is an auto increment loop and prints all the elements in the  container(arrays, vectors, list ques, etc)

Example to access array elements using for _each

char ar[] = { 't','r','i','s','h','a','a','n','k' };
for (int m : ar)//direclly printing with out inc/dec
cout << m <<"\t";


t r i s h a a n k
For each loop in C++


  • This is very simple. Here, the variable m will go to every element of the array ar and will take its value.
  • So, in the first iteration, m is the 1st element of array ar i.earr[0]In the second iteration, it is the 2nd element i.e. arr[1 ]and so on. 

Limitation of for each loop

  • It is applicable  only for arrays and container classes, it cannot be used for normal variables
  • It cannot be customized with conditions, I,e you can only print data from start to end

Why to use for_each

  • for_each loops improve the overall performance of code
  • It increases code readability


One comment on “For each loop in C++”

  • Kunal Kishor

    For each loop is basically used for accessing data from array, vector. .etc. It is designed to used when the Developer doesn’t know about the size of the data that are stored in Array . So, on that time for each loop will be used because under this loop we don’t have to describe the size . We just only declare a variable and all the accessed data are stored on this variable.