Loading...
C++ Ranged For Loop

C++ Ranged For Loop

In this tutorial, we will learn about the C++ ranged for loops and its best practices with the help of examples.


Ranged For Loop

  • Range-based for loop in C++ eas introduced Since C++ 11.
  • It executes a for loop over a range.
  • Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
  • This for loop is specifically used with collections such as arrays and vectors.

Its Syntax :

for (variable : collection) {
// body of loop
}

For example,

// initialize an int array
int num[3] = {1, 2, 3};
                      
// use of ranged for loop
for (int var : num) {
// code
}

Here, the ranged for loop iterates the array num from the beginning of to end. The int variable var stores the value of the array element in each iteration.

Its syntax is,

for (rangeDeclaration : rangeExpression) {
// code
}

In the above example,

  • rangeDeclaration - int var
  • rangeExpression - num
Working of Ranged for Loop in C++
Working of ranged for loop in C++

Example 1: Ranged for Loop Using Array

#include <iostream>     
using namespace std;
      
int main() {

    // initialize array  
    int numAry[] = {1, 2, 3, 4, 5, 6};
                                      
    // use of ranged for loop to print array elements  
    for (int i : numAry) {
        cout << i << " ";
    }

    return 0;
}

Output

1 2 3 4 5 6

In this example, we declared and initialized an int array named numAry. Here, we used the ranged for loop to print out the elements of numAry.

  • first iteration - i takes the value of the first member of the array, which is 1
  • second iteration - i takes the value of 2 and is then printed and so on.

Note: The ranged for loop automatically iterates the array from its beginning to its end. We do not need to specify the number of iterations in the loop.


Example 2: C++ Ranged for Loop Using Vector

#include <iostream>
using namespace std;
      
int main() {

    // declare and initialize vector  
    vector<int> num = {1, 2, 3, 4, 5, 6};
                                      
    // print vector elements 
    for (int i : num) {
        cout << i << " ";
    }

    return 0;
}

Output

1 2 3 4 5 6

Example 3: Declare Collection inside the Loop

#include <iostream>
using namespace std;
      
int main() {
    // define the collection in the loop itself
    for (int num : {1, 2, 3, 4, 5, 6}) {
        cout << num << " ";
    }
    return 0;
}

Output

1 2 3 4 5 6

Here, we have declared the collection within the loop itself i.e.

rangeExpression = {1, 2, 3, 4, 5, 6}

This is also a valid way of using the ranged for loop, and it works in the same way as when we use an actual array or vector.


C++ Ranged for Loop Good Practices

In the above examples, we have declared a variable in the for loop to store each element of the collection in each iteration.

int n[5] = {1, 2, 3, 4, 5};
                                      
// copy elements of n to var
for (int var : n) {
    // statement
}

However, it's better to write the ranged based for loop like this:

// access memory location of elements of n
for (int &var : n) {
    // statement
}

Notice the use of & before var. Here,

  • int var : n - Copies each element of n to the var variable in each iteration. This is not good for computer memory.
  • int &var : n - Does not copy each element of num to var. Instead, accesses the elements of n directly from n itself. This is more efficient.

Note: The & operator is known as the reference operator. We will learn more about it in C++ pointers.

Note: If we are not modifying the array/vector/collection within the loop, it is better to use the const keyword in range declaration.

// collection is not modified in the loop
for (const int &var : num) {
    // code
}

Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Ranged For Loop in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ while/do...while Loop.

- Related Topics