For-each loop in C++

For-each loop in C++

On this page we will discuss for-each loop in C++.One of the essential features in C++ is the For-Each loop, which simplifies the process of iterating through elements in a collection. In this article, we will delve deep into the For-Each loop, exploring its syntax, use cases, and advantages. By the end, you’ll have a solid understanding of how to leverage this loop construct in your C++ code for enhanced productivity and readability.

for each loop

For-Each Loop in C++ Explained

The For-Each loop, also known as the Range-Based for loop, was introduced in C++11. It provides an elegant and concise way to iterate through elements within a range-based container, such as arrays, vectors, or other containers that support iteration. The For-Each loop greatly simplifies the traditional For loop syntax, making the code more expressive and less prone to errors.

Syntax

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

Benefits of Using For-Each Loop

Common Use Cases of For-Each Loop

1. Iterating Through Arrays

For-each loop in C++ can be effectively used to iterate through arrays:

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

for (int num : numbers) {
    // Code to process each element in the array
}

2. Traversing Vectors

For-each loop can also be used to traverse vectors:

#include <vector>

std::vector fruits = {"apple", "banana", "orange"};

for (const std::string& fruit : fruits) {
    // Code to work with each fruit
}

3. Iterating Through Containers

You can use the For-Each loop with other containers, such as lists, maps, and sets:

#include <list>
#include <map>
#include <set>

std::list temperatures = {23.5, 26.1, 20.8, 19.9};

for (double temp : temperatures) {
    // Code to process each temperature reading
}

Example 1

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
Explanation: 

In the code, we have defined an integer array arr with five elements. The For-Each loop is used to iterate through the elements of the array and print them one by one. The loop variable x represents each element of the array during the iteration.

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

Example 3:

Run

#include<iostream>
using namespace std;
int main ()
{
  int n = 5;
  int items[n] = { 2, 4, 6, 8, 10 };
  cout << "Elements are: ";
  for (int i = 0; i < n; i++)
    {
      cout << " " << items[i];
    }
  cout << endl;
  int key = 6;
  cout << "element to be searched: ";
  cout << key;
  cout << endl;
for (int i:items)
    {
      if (i == key)
	{
	  cout << "element found" << endl;
	  return 0;
	}
    }
  cout << "element not found" << endl;
  return 0;
}

Output

Elements are: 2 4 6 8 10 
element to be searched: 6 
element found
Explanation: 
  1. The code initializes an integer variable n to 5, representing the size of the array items.
  2. An integer array items is declared and initialized with five elements: 2, 4, 6, 8, and 10.
  3. The program then prints the elements of the array using a traditional For loop, iterating from 0 to n-1 and printing each element.
  4. An integer variable key is defined and assigned the value 6, representing the element to be searched in the array.
  5. The program prints the value of key to indicate which element is being searched.
  6. The For-Each loop is used to iterate through the elements of the array items.
  7. During each iteration, the loop compares the current element i with the key.
  8. If a match is found, the program prints “Element found” and exits the program with return 0;.
  9. If the loop finishes without finding a match, the program prints “Element not found.”

Conclusion

The For-Each loop is a powerful addition to C++, providing an elegant and efficient way to iterate through container elements. Its simplicity, improved readability, and automatic handling of iteration boundaries make it a preferred choice over traditional For loops in many scenarios. By using the For-Each loop in your C++ code, you can enhance your productivity and produce cleaner, more maintainable code.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

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.