To iterate over an array in C++ in reverse order, you can use a for
loop starting from the last index to the first index.
In this example,
numbers
with some values.for
loop starting from the last index to iterate over each element of the array in reverse order.#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (int i = numbers.size() - 1; i >= 0; i--) {
std::cout << numbers[i] << std::endl;
}
return 0;
}
5 4 3 2 1
In this example,
fruits
with some values.for
loop starting from the last index to iterate over each element of the array in reverse order.#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> fruits = {"apple", "banana", "cherry"};
for (int i = fruits.size() - 1; i >= 0; i--) {
std::cout << fruits[i] << std::endl;
}
return 0;
}
cherry banana apple
In this tutorial, we learned How to Iterate Over an Array in Reverse Order in C++ language with well detailed examples.