0

C++ Arrays and range based for loop

I am not used to this code format. I need explanation for what is going on here. Also, explain what this format of range based for loop is more often used for ? #include <iostream> using namespace std; int main (){ int array[ 3 ] = {5, 2 , 3}; for (int x : array){ cout << x << " "; } return 0; } Link to run the program: cpp.sh/9fho

16th Jan 2017, 12:43 AM
Kourosh Azizi
Kourosh Azizi - avatar
4 odpowiedzi
+ 1
this loop is called a for-each loop, which is used to iterate over each element of an array. here, the integer x in the loop takes every value of the array in each loop run. In first run, x = 5 in second, x = 2 and in third, x = 3 the loop ends when all elements of the array are used.
16th Jan 2017, 1:38 AM
Nikunj Arora
Nikunj Arora - avatar
+ 1
it is used when dealing with arrays. using for loop :- for(int i = 0; i < length; i++) { cout << array[i]; } using for-each loop:- for(int i : array) { cout << i; } note that the variable i needs to be the same type as the elements of the array. advantage of using for-each is that you can use the loop without knowing the length of the array.
16th Jan 2017, 2:33 AM
Nikunj Arora
Nikunj Arora - avatar
+ 1
@Nikunj, thanks a lot my friend. Your explanation is just pure easy and clean to understand.
16th Jan 2017, 4:40 AM
Kourosh Azizi
Kourosh Azizi - avatar
0
Ok, can you give an example where for each loop can be used instead of regular for loop ? I have problem understanding where to use it.
16th Jan 2017, 2:07 AM
Kourosh Azizi
Kourosh Azizi - avatar