Printing an array in C++?
Just iterate over the elements. Like this:
for (int i = numElements - 1; i >= 0; i--)
cout << array[i];
Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.
Use the STL
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ranges>
int main()
{
std::vector<int> userInput;
// Read until end of input.
// Hit control D
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(userInput)
);
// ITs 2021 now move this up as probably the best way to do it.
// Range based for is now "probably" the best alternative C++20
// As we have all the range based extension being added to the language
for(auto const& value: userInput)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print the array in reverse using the range based stuff
for(auto const& value: userInput | std::views::reverse)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print in Normal order
std::copy(userInput.begin(),
userInput.end(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Print in reverse order:
std::copy(userInput.rbegin(),
userInput.rend(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
}