How to loop over an array in C++
Arrays are the most versatile and frequently used data structures that are used to store several values of the same datatype under the same name. This article is about accessing elements of the array using different types of loops provided in C++.
Using the for loop:
The for
loop is the most frequently used loop to loop over all the elements in the array. The loop iterates over a constant which has values between 0 and the size of the array. The elements can be accessed by using the subscript operator ([ ]
).
The following example illustrates the use of for loop for accessing elements in the array:
#include <iostream> int main() { int a[10]; for (int i = 0; i < 10; i++)//i is the loop variable { a[i] = i; } for (int i = 0; i < 10; i++) { std::cout << a[i]<<" "; } }
Output: 0 1 2 3 4 5 6 7 8 9
Using the while loop: Iterate through C++ array
The while loop is seldom used in looping over an array. Although, the basic principle remains the same. We use an external variable and its value is incremented inside the loop’s body( which can be done in the initialization statement of the for loop).
Example:
#include<iostream> int main() { int a[10]; for (int i = 0; i < 10; i++)//i is the loop variable { a[i] = i; } int i = 0;// the looping variable for while loop while (i < 10) { std::cout << a[i]<<" "; i++; } }
Output: 0 1 2 3 4 5 6 7 8 9
Using the do-while loop: Iterate an array
The do-while is implemented using the same principles as the while loop. However, the for loop or while loop would be the first preference. Choosing the do-while loop would be the last thing to do for looping over elements.
Example:
#include <iostream> int main() { int a[10]; for (int i = 0; i < 10; i++)//i is the loop variable { a[i] = i+1; } int i = 0;// the looping variable for while loop do { std::cout << a[i]<<" "; i++; } while (i < 10); }
Output 1 2 3 4 5 6 7 8 9 10
Using the range-based for loop:
Range-based for loop can be used when all elements of elements in an array are to be accessed. The syntax for range-based for loop is as follows
for(datatype variable name: array name)
where datatype is the data type of the elements in the array and the variable name is assigned to the value of the elements in the array in order.
Example:
#include <iostream> int main() { int a[10]; for (int i = 0; i < 10; i++)//i is the loop variable { a[i] = i; } for (int x : a) { std::cout << x << " "; //x equals the values i array in the corresponding iteration } }
The output is the same as the normal for loop.
Range-based for loop
can be used when looping all elements from the beginning of an array to its end. Because, of its small syntax it is used, by combining with auto keyword for the datatype name, frequently.
Leave a Reply