For each loop in C++

For each loop

Here, in this section, we will discuss for each loop in C++.

for each loop

How it works

Setting up a for loop is long you need to take care of initialization, condition(s), increment/decrement. In the case of arrays and vectors where the most frequent job is to print all items in them. For each loop was introduced in C++ by developers.

Syntax

for (variable : collection) {
    // statement(s)
}

Example 1

Print all elements of integer array
Run
#include<iostream>
using namespace std;
  
int main()
{
    int arr[] = {10, 20, 30, 40, 50};
  
    // introduced in C++11
    // allows to print each item of array/vector
    for (int x : arr)
        cout << x << " ";
   
    return 0;
}

Output

10 20 30 40 50

Example 2

Run
#include<iostream>
using namespace std;
  
int main()
{
    char arr[] = {'P', 'a', 'r', 't', 'y'};
  
    // introduced in C++11
    // allows to print each item of array/vector
    for (char i : arr)
        cout << i << " ";
   return 0;
}

Output

P a r t y
  • 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.