Range-Based for Loop in C++

C++ range-based for loops execute for loops over a range of values, such as all the elements in a container, in a more readable way than the traditional for loops.

Syntax:

for ( range_declaration : range_expression )     {        
// loop_statements here
  }
  • range_declaration: to declare a variable that will take the value of each element in the given range expression.
  • range_expression: represents a range over which loop iterates.

Example of Range-Based for Loop

The below example demonstrates the use of a Range-Based loop in a C++ program.

C++




// C++ Program to demonstrate the use of range based for
// loop in C++
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
  
    cout << "Printing array elements: " << endl;
    // range based for loop
    for (int& val : arr) {
        cout << val << " ";
    }
    cout << endl;
  
    cout << "Printing vector elements: " << endl;
    vector<int> v = { 10, 20, 30, 40, 50 };
  
    // range-based for loop for vector
    for (auto& it : v) {
        cout << it << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Printing array elements: 
10 20 30 40 50 
Printing vector elements: 
10 20 30 40 50 

Explanation:
The above program shows the use of a range-based for loop. Iterate through each element in an array (arr here) and a vector (v here) and print the elements of both.

for Loop in C++

In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the specified range of values. Basically, for loop allows you to repeat a set of instructions for a specific number of iterations.

for loop is generally preferred over while and do-while loops in case the number of iterations is known beforehand.

Similar Reads

Syntax of for Loop

The syntax of for loop in C++ is shown below:...

Flowchart of for Loop in C++

Flowchart of for Loop in C++...

Examples of for Loop in C++

Example 1...

C++ Nested for Loop

...

Multiple Variables in for Loop

...

C++ Infinite for Loop

...

Range-Based for Loop in C++

A nested for loop is basically putting one loop inside another loop. Every time the outer loop runs, the inner loop runs all the way through. It’s a way to repeat tasks within tasks in your program....

for_each Loop in C++

...