Range-Based for Loop in C++
C++ range-based for loops execute for loops over a range of values, such as all the elements in a container, in a more readable way than the traditional for loops.
Syntax:
for ( range_declaration : range_expression ) { // loop_statements here }
- range_declaration: to declare a variable that will take the value of each element in the given range expression.
- range_expression: represents a range over which loop iterates.
Example of Range-Based for Loop
The below example demonstrates the use of a Range-Based loop in a C++ program.
C++
// C++ Program to demonstrate the use of range based for // loop in C++ #include <iostream> #include <vector> using namespace std; int main() { int arr[] = { 10, 20, 30, 40, 50 }; cout << "Printing array elements: " << endl; // range based for loop for ( int & val : arr) { cout << val << " " ; } cout << endl; cout << "Printing vector elements: " << endl; vector< int > v = { 10, 20, 30, 40, 50 }; // range-based for loop for vector for ( auto & it : v) { cout << it << " " ; } cout << endl; return 0; } |
Printing array elements: 10 20 30 40 50 Printing vector elements: 10 20 30 40 50
Explanation:
The above program shows the use of a range-based for loop. Iterate through each element in an array (arr here) and a vector (v here) and print the elements of both.
for Loop in C++
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the specified range of values. Basically, for loop allows you to repeat a set of instructions for a specific number of iterations.
for loop is generally preferred over while and do-while loops in case the number of iterations is known beforehand.
Contact Us