How To Loop Over an Array in C++
Arrays are some of the most fundamental data structure in any programming language as they allow us to store a collection of elements of the same type in sequential memory locations, which is useful in accessing data more efficiently.
In this tutorial, we will guide you on various methods and techniques you can use to iterate over the elements of an array in C++.
C++ Declare Array
Before proceeding, it’s essential to know how to declare an array in C++.
The following example shows how to define an array of integers with 5 elements in C++:
int arr[5] = {1, 2, 3, 4, 5};
This code declares an array named arr
of type int
, containing five elements.
C++ Loop Array - Using the for loop
The for
loop is a simple and classic way of iterating through an array.
#include <iostream>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++)
{
std::cout << arr[i] << "\n";
}
}
In the above example, the for
loop starts with i = 0
and ends when i
is no longer less than 5
, incrementing i
after each iteration.
We can compile the code above and run it as shown:
g++ array_loop.cpp
./a.out
Output:
1
2
3
4
5
C++ Loop Array - Using The while loop
We can also use a while
loop to iterate over an array:
#include <iostream>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
int i = 0;
while (i < 5)
{
std::cout << arr[i] << "\n";
i++;
}
}
Unlike the for
loop, using a while
loop tends to be more verbose and requires unnecessary steps.
g++ arrays.cpp
./a.out
Output:
1
2
3
4
5
C++ Loop Array - The do-while loop
We also have the do-while
loop which is similar to the while
loop, with the exception of checking the condition at the end of the loop, ensuring the loop’s body runs at least once.
#include <iostream>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
int i = 0;
do
{
std::cout << arr[i] << "\n";
i++;
} while (i < 5);
}
C++ Loop Over Array - Range-based for loop (C++11 onwards)
The range-based for
loop, introduced in C++11, provides a more readable syntax when working with collections.
#include <iostream>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
for (const auto &value : arr)
{
std::cout << value << "\n";
}
}
In this case, value
represents each element in the array. The auto
keyword automatically infers the type of elements in the array, and the &
sign creates a reference to the original element, avoiding copying.
The const
keyword ensures that the value
can’t be modified within the loop.
Note: The size of an array is often represented by a separate variable, or calculated using sizeof(arr) / sizeof(arr[0])
. You might also consider using a std::array
or std::vector
in modern C++, as they provide more flexibility and additional utility functions.
Conclusion
In this post, we explored some basic methods of iterating over an array by using various types of loops or using range-based iteration as introduced in C++ version 11 and above.