Range-based for loop in C++
Range-based for loop
In this section, we will learn about the concept and implementation of range-based for loop in C++. Range based for loops are used to implement for loops over a specified range. This format of for loop is considered to be a more readable format of using for loop in C++ while writing codes.
Range-based For loop
In C++ programming language, we will see the syntax of range based for loop and along with it example code for the same. Range based for loops are used to implement for loops within a specified range.
Syntax:
for( range_declaration : range_expression ) loop_statement
Range Declaration :
a declaration of a named variable, whose type is the type of the element of the sequence represented by
range_expression
Range Expression :
any expression that represents a suitable sequence or a braced-init-list.
Loop statement :
any statement, typically a compound statement, which is the body of the loop.
Implementation of range based for loops in C++
Example:
The following code shows the use of range-based for loops.
#include<iostream> #include<vector>
using namespace std; int main() { vector v = { 0, 1, 2, 3, 4, 5 }; for (auto i : v) cout << i << ' '; cout << '\n'; for (int n : { 0, 1, 2, 3, 4, 5 }) cout << n << ' '; cout << '\n'; int a[] = { 0, 1, 2, 3, 4, 5 }; for (int n : a) cout << n << ' '; cout << '\n'; for (int n : a) cout << "Prime" << ' '; cout << '\n'; string str = "Prep"; for (char c : str) cout << c << ' '; cout << '\n'; }
Output:
0 1 2 3 4 5
0 1 2 3 4 5
Prime Prime Prime Prime Prime Prime
P r e p
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment