CPP Tutorials

Mastering the for_each Loop in C++


Imagine you’re hosting a party and you want to invite all your friends. In C++, the ‘for_each’ loop is like having a personal assistant who handles the task of sending invitations to each friend in your list. It automates the process of performing a specific action for every item in a collection.

Whether it’s printing each element, calculating their values, or any other action, the ‘for_each’ loop simplifies the task and makes the code more readable. By understanding how to use the ‘for_each’ loop, you can efficiently process collections and perform actions on each element. Let’s dive in and explore this powerful loop!

What Is the for_each Loop in C++?

The ‘for_each‘ loop in C++ is a specialized loop used to iterate over elements in a range, like arrays or containers, applying a provided function to each element. It simplifies code by removing the need for manual index tracking and incrementing. This loop enhances readability and is especially convenient for applying the same operation to all elements within a collection, making the code more concise and efficient.


<code>#include <algorithm> // Include the algorithm header

// Syntax of the for_each loop
for_each(start_iterator, end_iterator, function_or_lambda);


  • start_iterator: Points to the beginning of the range you want to iterate over.
  • end_iterator: Points to the end of the range you want to iterate over.
  • function_or_lambda: A function or lambda expression that will be applied to each element in the range.

How Is the for_each Loop Used in C++?

  • Include the Necessary Header: To use the ‘for_each‘ loop, include the ‘<algorithm>‘ header in your program.
  • Define the Range: Decide on the range (collection of elements) over which you want to iterate. It could be an array, vector, list, etc.
  • Create a Function or Lambda: Prepare a function or a lambda expression that you want to apply to each element during iteration. This function should take an element of the collection as a parameter.
  • Apply the for_each Loop: Use the ‘for_each‘ loop with the ranges ‘begin()‘ and ‘end()‘ iterators, along with the function or lambda you created.
  • Function Application: The defined function or lambda will be applied to each element in the range.
  • Effect of Function: The effect of the function or lambda on each element depends on what you want to achieve. It could be printing, modifying, calculating, etc.
  • Loop Completion: The loop will run through the entire range, applying the function to each element.

Real-life Example of ‘for_each‘ in C++

Let’s use a real-life example that involves managing a list of student grades using the ‘for_each‘ loop in C++.

Consider this scenario: you’re a teacher who has just finished grading exams and you have a list of scores for each student in your class. Now, you want to go through each grade and give extra credit: 5 points to each student’s score.

You could use the ‘for_each‘ function from the Standard Template Library (STL) in C++ to perform this task.

Here’s an example of how you could write such a program:

#include<algorithm> // for the for_each function

using namespace std;

int main() {
    // vector of grades
    vector<int> grades = {75, 80, 65, 89, 70};

    // we use for_each to iterate over each grade and add 5
    for_each(grades.begin(), grades.end(), [](int &grade) {
        grade += 5;

    // now, let's print the updated grades
    for(int grade : grades) {
        cout << grade << endl;

    return 0;




  • Vector Initialization: Create a vector named ‘grades‘ to store a list of grades.
  • Applying the for_each Loop: Utilize the ‘for_each‘ function from the Standard Template Library (STL) to apply a specified function to each element within the ‘grades‘ vector.
  • Lambda Function: Define a lambda function inside the ‘for_each‘ function. This lambda function increments each grade by 5.
  • Effect on Elements: The lambda function modifies each grade element by adding 5 to it.
  • Output and Verification: After the loop, print the modified grades to confirm the changes.

A Problem to Solve

Problem Statement:

You have a list of students and their respective scores on a test. The scores are stored in a vector. Write a program using the ‘for_each‘ loop that will:

  1. Display all the scores.
  2. Calculate and display the average score.
  3. Find and display the highest score.

Use this initial data for the scores: ‘{89, 95, 72, 84, 98, 88, 76}


  • The ‘for_each‘ loop takes in two iterators (beginning and end) and a function that is applied to each element in the range.
  • To find the sum of the scores, you can use a lambda function in the ‘for_each‘ loop.
  • The average can be calculated by dividing the total sum by the number of elements.
  • To find the highest score, use the ‘max_element‘ function from the STL.

Examples of Using the for_each Loop in C++

Let’s look at some examples to see how the ‘for_each‘ loop can be used in C++. We’ll provide the code, the expected output, and a step-by-step explanation of how the ‘for_each‘ loop is used.

Example 1

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // Using for_each loop to print each element
    std::cout << "Numbers in the vector: ";
    std::for_each(numbers.begin(), numbers.end(), [](int num) {
        std::cout << num << " ";
    std::cout << std::endl;

    return 0;


Numbers in the vector: 1 2 3 4 5


  • Loop Purpose: The ‘for_each‘ loop is used to go through each element of the ‘numbers‘ vector.
  • Action on Each Element: A lambda function is applied to each element during iteration.
  • Lambda Function: The lambda function prints the number followed by a space.
  • Output: The output shows each number in the vector separated by spaces.
  • Code Efficiency: The ‘for_each‘ loop simplifies iterating over elements and applying actions without explicitly managing indices.

Example 2

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<std::string> fruits = {"Apple", "Banana", "Orange", "Grapes"};

    // Using for_each loop to print each fruit
    std::cout << "Fruits in the list: ";
    std::for_each(fruits.begin(), fruits.end(), [](const std::string &fruit) {
        std::cout << fruit << " ";

    return 0;


Fruits in the list: Apple Banana Orange Grapes


  1. Loop Purpose: The ‘for_each‘ loop is used to go through each element in the ‘fruits‘ vector.
  2. Lambda Function: A lambda function is used inside the loop. It’s a small inline function that takes a fruit name as an argument.
  3. Printing: The lambda function’s task is to print the fruit name to the console.
  4. Iteration: The loop iterates over all elements in the ‘fruits‘ vector one by one.
  5. Output: The printed output shows each fruit name separated by spaces, indicating the successful iteration and printing process.

The Pros and Cons of Using the for_each Loop

Simplifies iteration over a collectionLimited control over iteration process
Provides a concise and readable syntaxLimited access to index or position of elements
Encourages a functional programming styleMay be less efficient for certain operations
Promotes code reusability and modularityRequires familiarity with function pointers or lambdas
Reduces the chance of off-by-one errorsNot suitable for all types of collections
The Pros and Cons of Using the for_each Loop

Key Takeaways

  • Iteration Control: The ‘for_each’ loop is used to execute a specific block of code for every item in a collection, such as an array or vector.
  • Simplified Code: It provides a more concise and readable way to iterate through elements compared to traditional ‘for’ or ‘while’ loops.
  • Lambda Function: A lambda function is often used with ‘for_each’, allowing customization of the action performed on each element.
  • Efficiency: ‘for_each’ can lead to more efficient and expressive code, reducing the chances of errors in manual iteration.
  • Applicability: It’s particularly useful for situations where you want to perform the same action on every item in a collection, like modifying or printing them.


Mastering the ‘for_each‘ loop in C++ can help you write more efficient and interactive programs. Whether you’re sending out party invitations or updating the status of each player in a game, the ‘for_each‘ loop allows your program to do something for each item in a collection. Remember to use the ‘for_each‘ loop correctly to avoid problems like infinite loops.

Frequently Asked Questions

  • What is the for_each loop in C++?
    The for_each loop in C++ is a way for us to repeat a block of code for each item in a collection.
  • Why do we need the for_each loop in C++?
    We need the for_each loop in C++ when we want our program to do something for each item in a collection.
  • How do we use the for_each loop in C++?
    We use the for_each loop in C++ by writing for_each(begin(collection), end(collection), [](int i) { code block });. The code block will be executed for each item in the collection.
  • Can using the for_each loop make code more confusing?
    Yes, if you use the for_each loop incorrectly, it can lead to problems like infinite loops. It’s important to understand how the for_each loop works and when to use it.
  • What are some examples of using the for_each loop in C++?
    Some examples include using the for_each loop to print numbers, using a return statement to skip the rest of the loop, and using the for_each loop to print only even or odd numbers.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Becoming a Full Stack Developer in 2023 How to Become a Software Engineer in 2023

Adblock Detected

Please consider supporting us by disabling your ad blocker!