Foreach Loop in C++

Foreach loop is also known as range-based for loop, it’s a way to iterate over elements through a container (like array, vector, list) in a simple and readable manner without performing any extra performance like initialization, increment/decrement, and loop termination or exit condition.

Syntax

The following is the syntax of for each loop −

for( data_type  element_variable__name : container_name ){
   // code to be executed
}

Here,

  • element_variable_name is the variable name given to the elements stored in a container.
  • container_name is the variable name of a container of any type such as an array, vector, list. etc.

How Foreach Loop Works?

  • The foreach loop iterates over all elements of the given container. The process starts with the first element, which is assigned to the variable as element_variable_name as shown in the code.
  • The loop then executes the body of the for each loop, allowing you to manipulate or use the elements.
  • After processing the current element, the loop moves to the next element in the container.
  • This process repeats until it reaches the last element of the container.

Example of Foreach Loop

In this example, the range-based for loop with a reference (int& num) allows you to directly modify each element of the vector.

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

int main() {
   vector<int> digits = {10, 20, 30, 40, 50};

   // Range-based for loop to modify each element
   for (int& num : digits) {
      num *= 2; // Double each number
   }

   for (int num : digits) {
      cout << num << " ";
   }
   cout << endl;

   return 0;
}

Output

20 40 60 80 100

Foreach Loop with Vector

The foreach loop can be used to iterate the over the vector elements.

Example

In this example, we are iterating and printing vector’s element by using foreach loop

#include <iostream>
#include <vector>
using namespace std;
int main() {
   vector<int> numbers = {1, 2, 3, 4};

   for (int num : numbers) {
      cout << num << " ";
   }
   return 0;
}

Output

1 2 3 4 

Foreach Loop with List

Similarly, the foreach loop can also be used to iterate over the list elements.

Example

Here, in this example we iterating and printing elements of list by using foreach loop

#include <iostream>
#include <list>

int main() {
   using namespace std;

   list<int> numbers = {10, 20, 30, 40, 50};

   for (int num : numbers) {
      cout << num << " ";
   }
   cout << endl;

   return 0;
}

Output

10 20 30 40 50 

For Loop Vs. Foreach Loop

The for loop executes the set of statements based on the given condition while the foreach loop (or, range-based for loop) iterates over the collection elements. Consider the following example to understand the difference between for and foreach in C++ −

Standard Method: for loop

The following is an example of for loop, where we are printing the elements of an integer array −

#include<iostream>
using namespace std;

int main() {
   // an Array
   int arr[] = {1,2,3,4};

   // Printing array elements using
   // for loop
   for (int i = 0; i <= 3; i++) {
      cout << i<<" ";
   }
   return 0;
}

Output

0 1 2 3

Foreach Loop Method

The following is an example of foreach loop, where we are iterating and printing the elements of an integer array −

#include<iostream>
using namespace std;
int main() {
   int arr[] = {1,2,3,4};
   // Where x is variable name provided to 
   // elements inside container
   for(int x: arr) {    
      cout<< x<<" ";
   }
   return 0;
}

Output

1 2 3 4

Foreach Loop with Non-container Type

Generally, foreach loop is used for iteration for container types like Array, vector, List, Deque, Set and Map etc. but it’s also used for Non-container type, which is iterable, meaning it must have begin() and end() that return iterators.

Traditional containers like vectors and all the rest mentioned above inherently meet these requirements so we don’t need to specifically specify begin() and end() to it.

Example

The following example demonstrates the working of foreach loop with a non-container type element −

#include <iostream>
#include <vector>
using namespace std;
class Iterable {
   public:
      // Constructor with initialization list
      Iterable(const vector<int>& v) : values(v) {}

      // Provide begin() and end() methods
      auto begin() const -> vector<int>::const_iterator {
         return values.begin();
      }
      auto end() const -> vector<int>::const_iterator {
         return values.end();
      }

   private:
      vector<int> values;
};

int main() {
   Iterable myIterable({1, 2, 3, 4, 5});

   for (int num : myIterable) {
      cout << num << " ";
   }
   cout << endl;

   return 0;
}

Output

1 2 3 4 5 

Here,

  • In the above code, the begin() method returns an iterator that points to the first element of the container whereas an end() method returns an iterator that points one position beyond the last element of the container.
  • Then loop iterate from iterator using for() over each element/value of vector printing each value to console.

Advantages of Foreach Loop

The following are the advantages of using Foreach loop in C++;

  • Simplicity − It reduces boiler plate code.
  • Readability − It has a simple way of writing code in an easy and readable manner compared to old standard traditional loop methods like for, while and do-while loop.
  • Safety − It reduces errors related to index management and edge cases.

Limitation of Foreach Loop

The following are some of the limitations of foreach loop −

  • Restricted to forward traversal − It does not give access to iterate in reverse order.
  • Non-interruptible traversal − There is no option to skip any element or break iteration in between before reaching the last index or last element.
  • No direct access of element while Iteration − There is no direct access to index or position of current element while iterating through foreach loop.

Applications of Foreach Loop

  • Read-only Iteration − The foreach loop is a good choice for read-only iteration, when the user wants to iterate through elements without any modifications, because the foreach loop provides cleaner and simple code.
  • Traversing over Container − The foreach loop is useful when we want to traverse over any kind of container like (Array, List, Vector) because this loop simplifies the process of iteration over elements of the container.
  • Simple Modification − It is useful when we want to perform any simple operation, because it gives simple, easy and readable code compared to the old standard method of writing iteration code.
  • Working with Non-Container Type − It also works with any type that meets the requirements of an iterable. which consist of begin() and end().
© 2024 All rights reserved. | Made With 🤍 By The_MAK Team