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 #
numbersis an array containing five integer elements.for (int number : numbers)defines a range-basedforloop.numberis initialized with each element ofnumbersin 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,
numberis a separateintvariable, so each iteration copies the current array element intonumber. - The loop body executes once for every element in the range.
- Range-based
forloops can be used with arrays and many C++ Standard Library containers. return 0;terminates the program successfully.