Table of contents
1.
Introduction
2.
What is Range Based for Loop C++?
3.
Example of Range Based for loop C++
3.1.
Example 1 - Ranged for loop using arrays
3.2.
C++
3.3.
 
3.4.
Example 2 - Ranged for loop using vector
3.5.
C++
3.6.
 
3.7.
Example 3: Declare Collection inside the Loop
3.8.
C++
4.
Benefits of the Range-Based Loop
5.
Frequently Asked Questions 
5.1.
In C++, what is a range-based for loop?
5.2.
Is a range-based loop in C++ faster?
5.3.
What is the difference between range-based for loop and normal for loop?
5.4.
What is a C++ iterator loop?
5.5.
What is the purpose of ‘auto’ in C++?
6.
Conclusion
Last Updated: Apr 17, 2024
Easy

Range Based for Loop C++

Author Kanak Rana
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Range Based for Loop C++

C++ is a general-purpose programming language for game development, software engineering, data structures, browser development, and operating system development.

The C++ language introduced a new idea of the range-based for loop in C++11 and later versions, which is far superior to the regular For loop.

Let's first start our discussion with ‘For’ loop.

What is Range Based for Loop C++?

The range-based for loop in C++ is a convenient syntax for iterating over elements in a container, such as arrays, vectors, or other iterable objects. It simplifies the process of iterating through each element of the container by automatically handling the iteration logic and eliminating the need for explicit index manipulation or iterator declaration. This loop iterates over each element of the container sequentially, making it especially useful for iterating through the entire contents of a container without the complexities of traditional loop constructs.

The implementation of loop iteration in a range-based for loop does not always necessitate extensive coding. It is a consecutive iterator that iterates over each block element (from beginning to end).

Use the range-based for loop to create loops that must iterate through a range, defined as anything that can be repeated.

For example:  std::vector or any other C++ Standard Library sequence whose range is determined by begin() and end() functions. 

The name declared in the for-range declaration portion is unique to the “for statement” and cannot be displayed again in the expression or statement. The auto keyword is preferred in the for-range declaration portion of the statement.

Syntax:

for (range_declaration: range_expression ) 
	loop block


In this syntax, there are three parameters:

🫳 range_declaration: It describes a variable with the same type as the collected elements represented by the range expression or a reference to that type.

🫳 range_expression: It describes an expression that represents the appropriate element sequence.

🫳 loop block: It describes the body of the range-based for loop, which includes one or more declarations that will be executed until the range expression is completed.

Example of Range Based for loop C++

The range-based for loop simplifies iteration over elements in containers without explicit index manipulation or iterator declaration.

Example 1 - Ranged for loop using arrays

  • C++

C++

#include <iostream>

int main() {
int arr[] = {1, 2, 3, 4, 5};
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Explanation: This loop iterates over each element of the array arr, storing each element in the variable num, and then prints the value of num.

Example 2 - Ranged for loop using vector

  • C++

C++

#include <iostream>
#include <vector>

int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Explanation: Similar to the array example, this loop iterates over each element of the vector vec and prints its value.

Example 3: Declare Collection inside the Loop

  • C++

C++

#include <iostream>
#include <vector>

int main() {
std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (auto& row : matrix) {
for (int num : row) {
std::cout << num << " ";
}
std::cout << std::endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Explanation: This loop demonstrates iterating over a 2D vector matrix, where each element is itself a vector. It iterates over each row of the matrix and then over each element in that row, printing them.

You can try and compile with the help of online c++ compiler.

Benefits of the Range-Based Loop

  • It is easy to use and has a simple syntax.
     
  • A range-based for loop does not involve calculating the number of variables in a container.
     
  • It recognizes the beginning and end elements of the containers.
     
  • We can easily change the size and elements of the container.
     
  • The elements are not duplicated.
     
  • It is way faster than the traditional for loop.
     
  • The auto keyword is typically used to determine the data type of container elements.

Frequently Asked Questions 

In C++, what is a range-based for loop?

Since C++ 11, there has been a range-based for loop. It runs a for loop over a set of values. As a more readable alternative to traditional for loop, this function operates over a range of values, such as all elements in a block.

Is a range-based loop in C++ faster?

Since it caches the end iterator, uses pre-increment, and only dereferences the iterator once, range-for is as fast as possible. Then, while range-for may be slightly faster, there's no reason not to use it because it's also easier to write (when appropriate).

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

The range-based for loop simplifies iteration over elements in containers by abstracting index manipulation, compared to the traditional for loop.

What is a C++ iterator loop?

An iterator is a C++ Standard Library object that can iterate over elements in a container and provide access to individual elements.

What is the purpose of ‘auto’ in C++?

The auto keyword is a straightforward way to declare a variable with a complex type. We can use auto to declare a variable whose initialization expression contains templates, pointers to functions, or pointers to members.

Conclusion

In this blog, we studied the details of range based for loop C++. We have also covered C++ as a language, definition, and example of the topic: Range Based for loop C++.

To know about more articles like range based for loop C++, check out the following:

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Live masterclass