range based for loop in c++

Loops  are the tools to make a instruction execute depends on how many times we want.

we all of us know loops in c++ are of three types :

  • For loop
  • while loop
  • do while loop


syntax of for loop is simple :

for(initialisation statement  ;  test condition ; update statement)

{

       ... set of statements ;
}

OK , now you are clear here yet .

my question is  what is the output of the following code :

string var = "aayush";

for(char c : var)

{

  cout << c << " ";
}


output is :

  a a y u s h

that's here is the concept of range based for loop. 

when for loop terminates corresponding to some type of  list like array , string , vector with only a single condition as loop argument , then this type of for loop is called range based for loop.

According to c++ refrenece :

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.

 

syntax : 


for ( range_declaration : range_expression )
 
  loop_statement

example code :

// Illustration of range-for loop
// using CPP code
#include <iostream>
#include <vector>
#include <map>

//Driver
int main()
{
// Iterating over whole array
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
std::cout << i << ' ';
std::cout << '\n';
// the initializer may be a braced-init-list
for (int n : {0, 1, 2, 3, 4, 5})
std::cout << n << ' ';
std::cout << '\n';

// Iterating over array
int a[] = {0, 1, 2, 3, 4, 5};
for (int n : a)
std::cout << n << ' ';
std::cout << '\n';
// Just running a loop for every array
// element
for (int n : a)
std::cout << "In loop" << ' ';
std::cout << '\n';
// Printing string characters
std::string str = "Geeks";
for (char c : str)
std::cout << c << ' ';
std::cout << '\n';

// Printing keys and values of a map
std::map <int, int> MAP({{1, 1}, {2, 2}, {3, 3}});
for (auto i : MAP)
std::cout << '{' << i.first << ", "
<< i.second << "}\n";
}

Comments