In this tutorial, we are going to explore the range-based for loop in the C++ programming language. The introduction of the range-based for loop in C++11 and subsequent versions brought a new approach to iterating through containers, offering a more efficient alternative to the traditional For loop. Unlike the standard For loop, the range-based for loop simplifies the iteration process without the need for extensive coding. It functions as a sequential iterator that traverses each element within a container across a specified range, from the initial to the final element.
Syntax
for (range_declaration : range_expression ) loop statement
- rangedeclaration: It is used to declare a variable whose type is the same as the types of the collected elements represented by the rangeexpression or reference to that type.
- range_expression: It defines an expression that represents the suitable sequence of elements.
- loop statement: It defines the body of the range-based for loop that contains one or more statements to be repeatedly executed till the end of the range- expression.
Note: If we don't know the data type of the container elements, we can use the auto keyword that automatically identifies the data type of the range_expression.
Program to print each element of the array using-range based for loop
Let's explore a scenario where we utilize the range-based for loop in C++ to display the integer and double arrays.
program.cpp
#include <iostream>
using namespace std;
int main ()
{
int arr1 [5] = { 10, 20, 30, 40, 50};
double darr [5] = { 2.4, 4.5, 1.5, 3.5, 4.0 };
// use range based for loop
for ( const auto &var : arr1 )
{
cout << var << " " ;
}
// use auto keyword to automatically specify the data type of darr container.
for ( const auto &var : darr )
{
cout << var << " " ;
}
return 0;
}
Output
10 20 30 40 50
2.4 4.5 1.5 3.5 4.0
Program to demonstrate the vector in range based for loop
Let's create a basic program to demonstrate the usage of a vector with a range-based for loop.
Program2.cpp
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int x; // declare integer variable
// declare vector variable
vector <int> vect = {5, 10 , 25, 20, 25};
// display vector elements
for ( int x : vect)
{
cout << x << " ";
}
return 0;
}
Output
5 10 25 20 25
Program to print the arrays using Range based for loop in C++ with reference
Let's explore an instance where we print the elements of an array using a range-based for loop in C++.
Program3.cpp
#include <iostream>
#include <array>
#include <cstdlib>
using namespace std;
int main(){
array<int, 7> data = {1, 3, -2, 4, 6, 7, 9};
cout << " Before updating the elements: " << endl;
for (int x : data){
cout << x << " ";
}
// pass the references
for (int &itemRef : data){
itemRef *= 3;
}
cout << endl << " After modification of the elements: " << endl;
for (int x : data){
cout << x << " ";
}
cout << endl;
return 0;
}
Output
Before updating the elements:
1 3 -2 4 6 7 9
After modification of the elements:
3 9 -6 12 18 21 27
Nested range-based for loop
When a loop is declared within the body of another loop, it is referred to as a nested for loop. Likewise, when a range is specified in a loop nested inside another range-based loop, this approach is recognized 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
}
In the preceding syntax, we declare a nested range-based for loop where we reference the inner and outer range-based for loop in C++.
Program to print the nested range-based for loop in C++
Illustrate a sample scenario showcasing the nested range-based for loop in the C++ programming language.
Range.cpp
#include <iostream>
using namespace std;
int main ()
{
int arr1[4] = { 0, 1, 2, 3 };
int arr2[5] = { 1, 2, 3, 4, 5 };
// 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 = 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 = 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 = 3 and j = 1
x = 3 and j = 2
x = 3 and j = 3
x = 3 and j = 4
x = 3 and j = 5
What is the difference between traditional for loop and range-based for loop?
A classic for loop is employed to iteratively run a block of code until the designated condition evaluates to true. This type of loop comprises three components: initializing the variable, setting the condition, and incrementing a counter if the condition holds true.
Syntax:
for ( variable_initialization; specify_condition; updated_counter)
{
// statement to be executed;
}
Range-based loop
On the flip side, a modern range-based for loop is accessible in C++ 11 and subsequent versions. It consists of two elements: the range declaration and the range expression. This loop is employed for iteratively running a block of code across a specified range.
Syntax
for ( range_declaration : range_ expression )
{
loop _statement;
// statement to be executed;
}
The rangedeclaration is employed to specify the variable type associated with the rangeexpression (container). The rangeexpression functions as a container that stores elements of the same type sequentially. The loopstatement describes the code that will be executed within the for loop.
Advantages of the range-based for loop
- It is easy to use, and its syntax is also simple.
- A range-based for loop does not require the calculation of the number of elements in a containers
- It recognizes the starting and ending elements of the containers.
- We can easily modify the size and elements of the container.
- It does not create any copy of the elements.
- It is much faster than the traditional for loop.
- It usually uses the auto keyword to recognize the data type of the container elements.
- It cannot traverse a part of a list.
- It cannot be used to traverse in reverse order
- It cannot be used in pointers.
- It does not offer to index of the current elements.