• Home
  • 5.7 Range-Based for Loop

5.7 Range-Based for Loop

View Categories

5.7 Range-Based for Loop

< 1 min read

Table of Contents

The range-based for loop provides a simplified way to iterate over the elements of a range, such as an array or a Standard Library container. It automatically obtains each element in sequence, eliminating the need to explicitly manage an index or iterator for basic iteration.

The range-based for loop was introduced in C++11 and is commonly used when the program needs to process every element of a collection.

Source Code #

#include <iostream>

int main()
{
    int numbers[] = {10, 20, 30, 40, 50};

    for (int number : numbers)
    {
        std::cout << number << '\n';
    }

    return 0;
}

Output #

10
20
30
40
50

Explanation #

  • numbers is an array containing five integer elements.
  • for (int number : numbers) defines a range-based for loop.
  • number is initialized with each element of numbers in sequence.
  • The loop automatically iterates from the first element to the last element of the array.
  • No index variable or explicit boundary condition is required.
  • By default, number is a separate int variable, so each iteration copies the current array element into number.
  • The loop body executes once for every element in the range.
  • Range-based for loops can be used with arrays and many C++ Standard Library containers.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

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