How to use range based for loop in C++?

In this post, we will learn about how range-based for loop in C++ works instead of traditional for loops. This range-based loop concept is in works from C++ 11 release. It iterates over a specific given range similar to traditional for loops but in the easiest declaration.

What is the difference between traditional for loop and range-based for loop?

In traditional for loops, we had to initialize the iterator first then have to set its exit condition and then we had to implement incrementing the logic i.e for(I=0; I <N; I++). In this example, ” I ” is initialized first and then I<N the exit condition is set over then the incrementing logic is implemented.
In the range-based for loops
for ( range_declaration : range_expression )

range_declaration: In the range declaration we have to declare a type of variable that is related with the range_expression or for auto-detection auto is a great choice, as it detects the type without human error.

range_expression: It is a  variable that is iterable or a sequence or a braced-init-list.

loop_statement: It is a statement that you want them to execute for their range times. i.e if the range is 5 thus this statement executes 5 times.


#include <iostream> 
#include <vector>  
int main()  
    std::vector<int> variable = {10, 21,32, 43, 54, 65};//Declaring vector integer variable 
    for (auto iterator : variable) //here iterator is auto type iterator and variable is assigned over which the iterator will iterate
        std::cout << iterator << ' '; 
    std::cout << '\n'; 
    for (int number : {10, 21,32, 43, 54, 65}) //In this instead of variable we have directly taken braced-init-list
        std::cout << number << ' ';

In the program above we declared an int vector named variable, Thus in for loop, we declared auto iterator thus it automatically detects the type and assigns it to the iterator. Thus std::cout << iterator << ‘ ‘; this line of code executes every time until range is not available for iteration.


10 21 32 43 54 65 

10 21 32 43 54 65


Leave a Reply

Your email address will not be published. Required fields are marked *