Print out digits of a number

I want to print out the digits of a number, and this program prints them but in reverse. How can I print them in order?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <conio.h>

using namespace std;

int Digits(int);

int main()
{
	int n;
	cout<<"n="; cin>>n;
	cout<<Digits(n);

	_getch();
}

int Digits(int n)
{
	if (n==0) return false; // I would prefer this 0 not to be shown
	if (n>0)
	cout<<n%10<<" ";
	return Digits(n/10);
	

}
They are printed in reverse because you print the least significant digit first, and then make the recursive call to print the other digits. You just need to reverse that logic.

The return value at line 19 looks wrong since Digits() returns an int. Maybe this should return 0 instead of false?

Note that your code won't work for a negative number.

Actually, it doesn't make much sense to me for Digits to return an int. I'd have it return a string or just not return anything at all and call it with Digits(cout, n);

If it returns a string then for efficiency you may want to do this in two stages:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void getDigits(string &result, int n)
{
    if (n) {
        getDigits(result, n/10);
        result += '0' + n%10;
}

string Digits(int n)
{
    if (n == 0) return "0";
    else {
        string result;
        getDigits(result, n);
        return result;
   }
}


If you do it this way the changing it to handle negative numbers is pretty easy.

Topic archived. No new replies allowed.