To iterate over an array in C++, you can use a for
loop or range-based iteration.
In this example,
numbers
with some values.for
loop to iterate over each element of the array and print the elements.#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++) {
cout << numbers[i] << endl;
}
return 0;
}
1 2 3 4 5
In this example,
fruits
with some values.#include <iostream>
#include <string>
using namespace std;
int main() {
string fruits[] = {"apple", "banana", "cherry"};
for (const auto &fruit : fruits) {
cout << fruit << endl;
}
return 0;
}
apple banana cherry
In this tutorial, we learned How to Iterate Over an Array in C++ language with well detailed examples.