Categories
Computer Science / Information Technology Language: C++

Range based for-loop

While C++ supports all the loops that C supports (for, while and do-while), C++ provides another loop called a range-based for loop.

The idea of the range-based for loop is to loop through a collection of elements and be able to easily access each element without having to worry about the length of the collection or incrementing and decrementing the loop counter. The syntax is as follows:

for (var_type var_name: collection) {
	statement_1;
	statement_2;
	…
	statement_n;
}
// Or
for (var_type var_name: collection)
	statement_1;

Here, the var_type is essentially the data type of the elements in the collection. This loop is entry controlled and the minimum number of iterations in this loop is 0 when the collection is empty. With each iteration, the values in the collection get assigned to var_name and this can be used inside of the loop.

Example:

#include <iostream>
using namespace std;
int main() {
    int num[] = {1, 2, 3, 4};
    for (int i: num)
        cout << i << " ";
    return 0;
}

Output: 1 2 3 4

Use of auto keyword

We do not have to explicitly provide the type of the variable in the range-based for loop. Instead, we can use the auto keyword. This tells the C++ compiler to deduce the type of the collection elements itself. Consider the following example:

#include <iostream>
using namespace std;
int main() {
    int num[] = {1, 2, 3, 4};
    for (auto i: num)
        cout << i << " ";
    return 0;
}

Output: 1 2 3 4

Here the compiler figures out that the variable i has to iterate through a collection of integer elements and hence implicitly considers the data type of i as int.

Iterate through the initialiser list

The range-based for loop doesn’t mandate the collection to be strictly a variable. We can use the loop to iterate through the initialiser list too. This is demonstrated in the following examples:

Example 1
#include <iostream>
using namespace std;
int main() {
    for (auto i: {1, 2, 3, 4})
        cout << i << " ";
    return 0;
}

Output: 1 2 3 4

Example 2
#include <iostream>
using namespace std;
int main() {
    for (auto i: "String")
        cout << i << " ";
    return 0;
}

Output: S t r i n g

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page