×

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a sequential generator that iterates each container element across a set of values (from beginning to end). This for loop is specifically used with collections such as arrays and vectors.

Syntax:

for (range_of_declaration : range_of_expression ) {
	// program code
}  
  • Range_of_declaration: It's used to define a variable with the same type as the accumulated items indicated by the range expression or a value to that type.
  • Range_of_expression: It defines a range expression that represents the appropriate sequence of items.
  • Program code: It specifies the content of the range-based for loop, which comprises one or even more lines to be repeated until the range-expression is finished.

We may use the auto keyword to automatically identify the data type of the range expression if we are not familiar with the data type of the contained items.

C++ Range-based For Loop

Fig. Ranged for Loop working

Range based For Loop Using Array:

This method is explained below using an example.

Example:

#include <iostream>
using namespace std;


int main() {


    // initializing an array  
    int numArrays[] = {10, 20, 30, 40, 50};


    // using ranged for loop to print the array of given elements  
    for (int x : numArrays) {
        cout << x << " ";
    }
  
    return 0;
}

Output:

10 20 30 40 50

Explanation:

We declared and initialised an int array namely numArrays in this example. To print the items in numArrays, we utilised the ranged for loop.

The first iteration accepts the value of an array's first element, which is 10, the second iteration uses the input of 20 and prints it, and so on.

The ranging for loop generates a sequence the array from start to finish automatically. The loop's number of iterations does not need to be specified.

Range based For Loop Using Vector:

This method is explained below using an example.

Example:

#include <iostream>
#include <vector>
using namespace std;


int main() {


    // declaring and initializing vector  
    vector<int> num_vect = {10, 20, 30, 40, 50};


    // printing the vector elements  
    for (int x : num_vect) {
        cout << x << " ";
    }
  
    return 0;
}

Output:

10 20 30 40 50

Explanation:

We declared and initialised a vector<int> array namely num_vect in this example. To print the items in num_vect, we utilised the ranged for loop.

The first iteration accepts the value represented by int x of an array's first element, which is 10, the second iteration uses the input of 20 and prints it, and so on.

Declaring a Collection inside the For Loop:

This method is explained below using an example.

Example:

#include <iostream>


using namespace std;


int main() {


    // defining the collection inside the loop itself
    for (int x : {10, 20, 30, 40, 50}) {
        cout << x << " ";
    }


    return 0;
}

Output:

10 20 30 40 50

Explanation:

The collection has been defined within the loop itself, i.e.

Ranged_Expression = {1, 2, 3, 4, 5}

This is also a legal technique to use the rangedg for loop, and it functions similarly to using a real array or vector.

Best Practices for C++ Ranged For Loops:

In each iteration of the for loop in the examples above, we declared a variable to hold every element of the collection.

int nums[3] = {10, 20, 30};


// copying the elements of nums to vars
for (int vars : nums) {
    // programming code
}

But it's preferable to write the range based for loop like follows:


// accessing the memory location of elements of nums
for (int &vars : nums) {
    // programming code
}

We should notice how & is used before var.

int vars: nums - In each iteration, replicates every element of nums here to vars variable. This is detrimental to computer memory.

int &vars: nums - Doesn't really replicate all of nums' elements to vars. Instead, nums' elements are accessed straight from nums. This is more practical.

The reference operator is represented by the & symbol and the C++ pointers will teach us more about it.

C++ Range-based For Loop

Fig. Address pointer working in ranged for Loop

Note: It is preferable using the const keyword in ranged declaration if we are not changing the array/vector/collection inside the loop.

Advantages of using Range-based for loop:

  • It's simple to use, and the syntax is straightforward.
  • The number of components in a container does not need to be calculated in a range-based for loop.
  • It detects the containers' beginning and ending components.
  • We can simply change the container's size and components.
  • It does not duplicate the components in any way.
  • It's a lot quicker than the standard for loop.
  • The auto keyword is commonly used to determine the data type of container components.

Disadvantages of using Range-based for loop:

  • It is unable to traverse a section of a list.
  • It can't be utilised to go backwards in time.
  • It is not suitable for usage in pointers.
  • It does not include a current element index.

Related Topics

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

C++ First Program

Let's write a simple basic program structure of C++, its compilation and its execution (how it runs). This program is compiled using GCC compiler. Open any editor to write C++ program. #include<iostream>   using namespace std;   int main(){       cout<<"Welcome to C++ program"<<endl;   } Output...

2 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.