Tutorial Study Image

Range Based for loop in C++


August 24, 2022, Learn eTutorial
1207

The use of for loop, while loops, and do while loops are clearly discussed in the previous tutorial. As we discussed in the previous tutorial we will use for loop in the C++ when the number of iterations is known ahead of time. When the number of iterations is unknown but the loop termination condition is known, we will use while loops in C++. If the code needs to be executed at least once, such as in menu-driven programs, then we will use a do while loop.

 In this tutorial let us discuss the more advanced looping techniques in C++. The more advanced looping techniques in C++ are :

  1.  Range_ based for loop in C++
  2.  for each loop in C++

Range Based for loop in C++

The range-based for loop in the C++ programming language will be covered in this topic. In C++11 and later versions, the C++ language introduced a new concept of the range-based for loop, which is far better compared to the regular For loop. A range-based for loop does not necessarily require a large coding in order to implement for loop iteration. It is a sequential iterator that iterated over each element of the container ( right from the beginning to the end).

Syntax


for (range_declaration : range_expression ) 
{
   loop statement 
}
  • range_declaration: It is used to declare a variable whose type will be the same as the types of the collected elements represented by the range expression or reference to that type.
  • range_expression: it defines an expression that represents the appropriate sequence of elements.
  • loop_statement: it defines the body of the range-based for loop, which contains one or more statements that will be executed repeatedly until the end of the range_expression.

For example,


// initialize an int array
int num_array[3] = {1, 2, 3};

// use of ranged for loop
for (int i: num_array) {
    // code
}

In the above example,

  • range_declaration - int i 
  • range_expression - num_array
Range Based for loop in C++

Note: Suppose if we don't know the data type of the container elements, we can use the auto keyword, which determines the data type of the range expression automatically.

Using a range-based for loop, let us write a program to print each element of an array

Let's take a look at a C++ range-based for loop example that prints an int and double array

Example : Range Based for Loop


#include <iostream>  
using namespace std;  
int main ()  
{  
int int_array[5] = { 1, 2, 3, 4, 5};  
double double_array [5] = { 4.2, 5.7, 4.8, 8.5, 4.0 };  
  
// use range based for loop  
for ( const auto &var : int_array)  
{  
cout << var << " " ;  
}  
// use auto keyword to automatically specify the data type of darr container.   
for ( const auto &var : double_array)  
{  
cout << var << " " ;  
}  
return 0;  
}

Output:

100 200 300 400 500
4.2 5.7 4.8 8.5 4.0 

Let's take a look at a C++ range-based for loop example that prints vector elements.

A vector is just a dynamically sized array. It contains a nearly infinite number of homogenous items (that is, objects of the same kind) that can be easily accessed by their position within the list. You don't need to explicitly use commands like new int[size] or delete[] my array because the underlying array will automatically adjust in size as needed.

Example: A program to demonstrate the vector in a range-based for loop.


#include <iostream>  
#include <vector>  
using namespace std;  
  
int main()  
{  
    int x; // declare integer variable  
    // declare vector variable  
    vector <int> vect = {10, 15 , 20, 25, 30};  
      
    // display vector elements  
    for ( int x : vect)  
    {  
        cout << x << " ";  
    }  
    return 0;  
} 

Output:

10 15 20 25 30 

Nested range-based for loop

When a loop is defined within the body of another loop, it is referred to as a nested for loop. Similarly, defining a range in a loop within another range-based loop is known as a nested range-based for loop.

Syntax:
 


for ( int x : range_expression) // outer loop  
{  
for ( int y : range_expression) // inner loop  
{  
  // statement to be executed  
}  
  // statement to be executed  
} 

We define one range-based for loop inside another loop in the above syntax. In C++, this is referred to as an inner and outer range-based for loop.

A C++ programme to print nested range-based for loops


#include <iostream>  
using namespace std;  
int main ()  
{  
int arr1[5]  = { 0, 1, 2, 3,4 };  
int arr2[6] = { 1, 2, 3, 4, 5,6 };  
// use nested range based for loop  
for ( int x : arr1 )  
{  
// declare nested loop  
for ( int y : arr2 )  
{  
cout << " x = " << x << " and j = " << y << endl;  
}  
}  
return 0;  
} 

Output:

 x = 0 and j = 1
 x = 0 and j = 2
 x = 0 and j = 3
 x = 0 and j = 4
 x = 0 and j = 5
 x = 0 and j = 6
 x = 1 and j = 1
 x = 1 and j = 2
 x = 1 and j = 3
 x = 1 and j = 4
 x = 1 and j = 5
 x = 1 and j = 6
 x = 2 and j = 1
 x = 2 and j = 2
 x = 2 and j = 3
 x = 2 and j = 4
 x = 2 and j = 5
 x = 2 and j = 6
 x = 3 and j = 1
 x = 3 and j = 2
 x = 3 and j = 3
 x = 3 and j = 4
 x = 3 and j = 5
 x = 3 and j = 6
 x = 4 and j = 1
 x = 4 and j = 2
 x = 4 and j = 3
 x = 4 and j = 4
 x = 4 and j = 5
 x = 4 and j = 6

What distinguishes range-based for loop from traditional for loop?

A traditional for loop is used to execute the block of code repeatedly until the specified condition is met. A traditional for loop has three parameters: variable initialization, condition specification, and a counter that is incremented by one if the condition remains true. On the other hand, C++ 11 and later versions include a new range-based for loop. There are two parameters: range declaration and range_ expression. It is also used to execute a block of code over and over again.

Benefits of using a range-based loop

  • It is simple to use and has simple syntax.
  • A range-based for loop does not require the number of elements in a container to be calculated.
  • It recognizes the containers' beginning and ending elements.
  • We can easily change the container's size and elements.
  • It does not make a duplicate of the elements.
  • It is significantly faster than the traditional for loop.
  • It typically employs the auto keyword to determine the data type of container elements.

The disadvantage of the range-based for loop

  • It is unable to traverse a portion of a list.
  • It cannot be used to travel in the opposite direction.
  • It is incompatible with pointers.
  • The current elements' index is not provided.