In this C++ tutorial, you will learn about for-each statement, its syntax, and how to use for-each statement to iterate over the elements of a given collection, with examples.

C++ Foreach

C++ Foreach statement can be used to iterate over the elements of a collection and execute a block of statements for each of the element.

The syntax of C++ Foreach statement is given below.

for (int element: arr) {
   //statement(s)
}

Examples

ADVERTISEMENT

1. Foreach element in array

In this example, we shall use foreach statement, to find the number of even numbers in an integer array.

C++ Program

#include <iostream>
using namespace std;

int main() {
   int nums[] = {4, 9, 6, 72, 31, 44};
   int even = 0;

   for (int num: nums) {
      if (num % 2 == 0)
         even++;
   }
   cout << even;
}

Output

4

2. Foreach character in string

In this example, we shall use foreach statement, to execute a set of statements for each character in a string.

C++ Program

#include <iostream>
using namespace std;

int main() {
   string str = "tutorialkart";
   
   for (char ch: str) {
      cout << ch << "  ";
   }
}

Output

t  u  t  o  r  i  a  l  k  a  r  t

In the following program, we shall use foreach statement, to count the number of vowels in a char array.

C++ Program

#include <iostream>
using namespace std;

int main() {
   char charArr[] = {'t','u','t','o','r','i','a','l','k','a','r','t'};
   int vowels = 0;

   for (char ch: charArr) {
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
         vowels++;
   }
   cout << vowels;
}

Output

5

3. Foreach element in vector

In the following program, we shall print elements of Vector using Foreach statement.

C++ Program

#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<int> nums;
   nums.push_back(24);
   nums.push_back(81);

   for(int num: nums)
      cout << num << " ";
}

Output

24 81

Conclusion

In this C++ Tutorial, we learned how to use C++ foreach statement to execute a block of statements for each element in a collection or array of elements.