Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C++ - ITERATING ARRAY USING FORRANGE


In the previous tutorial we have seen how to iterate an array.


for (int i = 0; i <= 4; i++)
{
	cout << arr[i] << endl;
}

Now, let us see the easiest way to iterate an array.


Iterating Array using 'for range' loop


We will create an Array with five values, Mohan, John, Paul, Kriti and Salim.


Example :



#include <iostream>
using namespace std;

int main() {
    
    string arr[] = {"Mohan", "John", "Paul", "Kriti", "Salim"};

    for (string str : arr) {
        cout << str << endl;
    }
    
    return 0;   
}


Output :



  Mohan
  John
  Paul
  Kriti
  Salim

So, in the above code we have created a Array and initialised to the variable arr.


string arr[] = {"Mohan", "John", "Paul", "Kriti", "Salim"};

In the below way the values are positioned in the Array,

java_Collections

So, as we can see the elements are positioned as 0, 1, 2, 3 and 4.


Then we have the for range loop.


for (string str : arr)

That takes the values of the array arr one by one and puts in the variable str.


Let us look at all the iterations of for range loop.


for (string str : arr) {
	cout << str << endl;
}

1st Iteration


So, in the first Iteration, the first value i.e. Mohan is taken from the first location and put into the variable str.

java_Collections
java_Collections

And the print statement,


cout << str << endl;

Prints the value of str.

Output :



  Mohan

2nd Iteration


Then in the second Iteration, the second value i.e. John is taken from the second location and put into the variable str.

java_Collections
java_Collections

And the print statement,


cout << str << endl;

Prints the value of str.

Output :



  Mohan
  John

Similarly, in 5 iterations all the values are printed.

Output :



  Mohan
  John
  Paul
  Kriti
  Salim