Programming Exercise

I have copy/paste my code below for a program. However, I need the numbers to be output in the reverse order than they are currently outputted. For example, if the user enters the number 5432, I need the output to be 5 4 3 2 (Not 2 3 4 5). Please advise on the simplest form to do so. Thanks!

#include <iostream>

using namespace std;

int main()
{
int digit;


cout << "Enter a positive number: " << endl;
cin >> digit;
if (digit <= 0)
return main();

do
{
cout << digit % 10 << " ";
digit /= 10;
}
while (digit > 0);
return 0;
}
convert it to a string and print backward.
Your return main() statement results into an infinit recursion causing a stack overflow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using std::cin;        // Avoid "using namespace std"
using std::cout;

int main(int argc, char *argv[])
{
    int digit;

    cout << "Enter a positive number: " << endl;
    cin >> digit;
    if (digit > 0)
    {
        do
        {
            cout << digit % 10 << " ";
            digit /= 10;
        }
        while (digit > 0);
    }
    return 0;

}
Topic archived. No new replies allowed.