Blog / October 3, 2023 / 4 mins read / By Suneet Agrawal

For and Foreach Loop in C++

When it comes to repetitive tasks in programming, loops are a powerful and versatile tool that can simplify your code and make it more efficient. In C++, two commonly used loops are the for loop and the for each loop. In this comprehensive guide, we’ll explore both types of loops in C++ and provide you with various examples to help you master their usage.

Anatomy of a for Loop

Before we dive into examples, let’s review the basic structure of a for loop in C++:

for (initialization; condition; increment/decrement) {
    // Code to be executed
}

Here’s what each part does:

  • Initialization: This part is executed only once at the beginning of the loop. It typically initializes a loop control variable (e.g., int i = 0).
  • Condition: The loop continues as long as the condition is true. When the condition becomes false, the loop terminates. If the condition is false from the start, the loop may not execute at all.
  • Increment/Decrement: This part is executed at the end of each iteration and is usually used to modify the loop control variable (e.g., i++ or i–).
  • Code to be executed: The block of code enclosed in curly braces {} is the body of the loop. It’s executed repeatedly until the condition becomes false.

Printing Numbers with a for Loop

#include <iostream>

int main() {
    for (int i = 1; i <= 5; i++) {
        std::cout << i << " ";
    }

    return 0;
}

Output:

1 2 3 4 5

In this example, we use a for loop to print numbers from 1 to 5. The loop control variable i is initialized to 1, and the loop continues as long as i is less than or equal to 5. After each iteration, i is incremented by 1.

Sum of Numbers with a for Loop

#include <iostream>

int main() {
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        sum += i;
    }

    std::cout << "Sum of numbers: " << sum << std::endl;

    return 0;
}

Output:

Sum of numbers: 15

In this example, we calculate the sum of numbers from 1 to 5 using a for loop. The sum variable accumulates the values of i in each iteration.

Anatomy of a for each Loop

The for each loop, also known as the range-based for loop, is a more recent addition to C++ and simplifies the iteration over elements in a container, such as an array or a collection. Here’s the basic structure of a for each loop:

for (datatype element : container) {
    // Code to be executed for each element
}

In this loop:

  • datatype is the type of elements in the container.
  • element is a variable that takes on the value of each element in the container in each iteration.
  • container is the collection or sequence of elements you want to iterate over.

Iterating Over an Array with a for each Loop

#include <iostream>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};

    for (int number : numbers) {
        std::cout << number << " ";
    }

    return 0;
}

Output:

1 2 3 4 5

In this example, we use a for each loop to iterate through an array of integers and print each element. The loop automatically handles the iteration, and you don’t need to manage an index variable like in the previous for loop example.

Sum of Numbers with a for each Loop

#include <iostream>
#include <vector>

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

    for (int number : numbers) {
        sum += number;
    }

    std::cout << "Sum of numbers: " << sum << std::endl;

    return 0;
}

Output:

Sum of numbers: 15

Here, we calculate the sum of numbers stored in a std::vector using a for each loop. The loop automatically iterates through the container, making it convenient for working with collections.

Conclusion

In C++, both the for loop and the for each loop are essential tools for controlling the flow of your program when you need to repeat a block of code multiple times or iterate through collections. By mastering these loops and understanding their differences, you can make your code more efficient and concise. Experiment with the provided examples and practice using both types of loops in your own programs to become proficient in their usage.

Comments