Course Content
C++ Introduction
0/1
C++ Variables & Constants
0/1
C++Scope of Variable
0/1
C++ Keywords & Identifiers
0/1
C++ Data Types
0/1
C++ Basic I/O
0/1
C++ Type Conversion
0/1
C++ Operators
0/1
C++ Comments
0/1
C++ If-else
0/1
C++ Ternary Operator
0/1
C++ for Loop
0/1
C++ Ranged for Loop
0/1
C++ while/do-while Loop
0/1
C++ break Statement
0/1
C++ Continue Statement
0/1
C++ switch Statement
0/1
C++ goto Statement
0/1
C++ Functions
0/1
C++ User-defined Functions
0/1
C++ Default Arguments
0/1
C++ Storage Class
0/1
C++ Recursion
0/1
C++ Return by Reference
0/1
C++ Arrays
0/1
C++ Multi-dimentional Arrays
0/1
C++ Arrays & Function
0/1
C++ String
0/1
C++ Structure
0/1
C++ Structure & Functions
0/1
C++ Pointers to Structure
0/1
C++ Pointers
0/1
C++ Void Pointers
0/1
C++ Pointers & Arrays
0/1
C++ Pointers & Functions
0/1
C++ Dynamic Memory Allocation
0/1
C++ OOPs Concepts
0/1
C++ Objects and Class
0/1
C++ Constructors
0/1
C++ Destructors
0/1
C++ Constructor Overloading
0/1
C++ Objects & Function
0/1
C++ Enumeration
0/1
C++ Inheritance
0/1
C++ Inheritance Access Control
0/1
C++ Inheritance Types
0/1
C++ Polymorphism
0/1
C++ Function Overloading
0/1
C++ Function Overriding
0/1
C++ Operator Overloading
0/1
C++ Friend Function
0/1
C++ Virtual Function
0/1
C++ Abstract Class & Pure Virtual Function
0/1
C++ Encapsulation
0/1
C++ Abstraction
0/1
C++ Templates
0/1
C++ Exception Handling
0/1
C++ Multithreading
0/1
C++ Standard Library
0/1
C++ Programming Tutorials
About Lesson

C++ Ranged For Loop

In this tutorial, we will learn about the C++ ranged for loops and its best practices with the help of examples.


Ranged For Loop

  • Range-based for loop in C++ eas introduced Since C++ 11.
  • It executes a for loop over a range.
  • Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
  • This for loop is specifically used with collections such as arrays and vectors.

Its Syntax :

for (variable : collection) {
// body of loop
}

For example,

// initialize an int array
int num[3] = {1, 2, 3};
                      
// use of ranged for loop
for (int var : num) {
// code
}

Here, the ranged for loop iterates the array num from the beginning of to end. The int variable var stores the value of the array element in each iteration.

Its syntax is,

for (rangeDeclaration : rangeExpression) {
// code
}

In the above example,

  • rangeDeclaration – int var
  • rangeExpression – num
Working of Ranged for Loop in C++
Working of ranged for loop in C++

Example 1: Ranged for Loop Using Array

#include <iostream>     
using namespace std;
      
int main() {

    // initialize array  
    int numAry[] = {1, 2, 3, 4, 5, 6};
                                      
    // use of ranged for loop to print array elements  
    for (int i : numAry) {
        cout << i << " ";
    }

    return 0;
}

Output

1 2 3 4 5 6

In this example, we declared and initialized an int array named numAry. Here, we used the ranged for loop to print out the elements of numAry.

  • first iteration – i takes the value of the first member of the array, which is 1
  • second iteration – i takes the value of 2 and is then printed and so on.

Note: The ranged for loop automatically iterates the array from its beginning to its end. We do not need to specify the number of iterations in the loop.


Example 2: C++ Ranged for Loop Using Vector

#include <iostream>
using namespace std;
      
int main() {

    // declare and initialize vector  
    vector<int> num = {1, 2, 3, 4, 5, 6};
                                      
    // print vector elements 
    for (int i : num) {
        cout << i << " ";
    }

    return 0;
}

Output

1 2 3 4 5 6

Example 3: Declare Collection inside the Loop

#include <iostream>
using namespace std;
      
int main() {
    // define the collection in the loop itself
    for (int num : {1, 2, 3, 4, 5, 6}) {
        cout << num << " ";
    }
    return 0;
}

Output

1 2 3 4 5 6

Here, we have declared the collection within the loop itself i.e.

rangeExpression = {1, 2, 3, 4, 5, 6}

This is also a valid way of using the ranged for loop, and it works in the same way as when we use an actual array or vector.


C++ Ranged for Loop Good Practices

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

int n[5] = {1, 2, 3, 4, 5};
                                      
// copy elements of n to var
for (int var : n) {
    // statement
}

However, it’s better to write the ranged based for loop like this:

// access memory location of elements of n
for (int &var : n) {
    // statement
}

Notice the use of & before var. Here,

  • int var : n – Copies each element of n to the var variable in each iteration. This is not good for computer memory.
  • int &var : n – Does not copy each element of num to var. Instead, accesses the elements of n directly from n itself. This is more efficient.

Note: The & operator is known as the reference operator. We will learn more about it in C++ pointers.

Note: If we are not modifying the array/vector/collection within the loop, it is better to use the const keyword in range declaration.

// collection is not modified in the loop
for (const int &var : num) {
    // code
}

 

Exercise Files
No Attachment Found
No Attachment Found
error: Content is protected !!