This post will discuss how to print the contents of an array in reverse order in C++.

1. Using Array Indices

A naive solution is to loop through the array elements and print each element.

Download  Run Code

Output:

40 30 20 10

 
The above code uses the sizeof operator for determining the array size. We can also create a template that deduces the size of the array from its declared type.

Download  Run Code

Output:

40 30 20 10

2. Using std::copy function

Another good alternative is to use the output iterator std::ostream_iterator to print array contents to the output stream std::cout. We can do it with the help of std::copy, which takes the reverse iterator to the starting and ending positions of the array and the output iterator.

Download  Run Code

Output:

40 30 20 10

 
With C++17, we can use std::copy with std::experimental::ostream_joiner which is defined in header <experimental/iterator>. It is a single-pass output iterator which can write successive array elements into the std::cout, using the << operator, separated by a delimiter between every two elements.

Run Code

Output:

5 4 3 2 1

3. Using Iterators

We can get iterators to the array with the help of std::cbegin and std::cend, which are introduced in C++11. The idea is to start a loop from std::cend, which returns a constant iterator to the array’s end. Then we iterate backward and print each element till we reach std::start, which returns a constant iterator to the beginning of the array.

Download  Run Code

Output:

40 30 20 10

4. Using std::for_each function

We can also use std::for_each that takes an input range defined by two iterators and applies a function on every element of that range. The function can be a unary function or an object of a class overloading the ()operator or a lambda expression.

Function


Download  Run Code

Class


Download  Run Code

Lambda


Download  Run Code

Output:

5 4 3 2 1

That’s all about printing the contents of an array in reverse order in C++.