-6

Possible Duplicate:
Identify the digits in a given number.

I need to print each digit of number without convert it to string. It's possible? For example:

int n = 1234;
int x;

while( ?? ) {
  x = ??
  printf("%d\n", x); 
}

it prints:

1
2
3
4

I have no idea how to do this. Thanks in advance.

Community
  • 1
  • 1
Jack
  • 16,276
  • 55
  • 159
  • 284

3 Answers3

3

Unless you tell me this isn't homework, I won't give the full answer.

Note that x / 10 gives you x stripped of the last digit. So 123 / 10 = 12, 45 / 10 = 4, etc.

And note that x % 10 gives you the last digit of x. So 123 % 10 = 3, 45 % 10 = 5, etc.

Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97
2

This actually touches on number theory / mathematical methods. You can write a number 1234, for example, as 1x10^3 + 2x10^2 + 3x10^1 + 4x10^0. Now think about how you can use % (mod) and / (integer division) to extract each digit.

Kevin
  • 53,822
  • 15
  • 101
  • 132
2

If you know the maximum number of digits, you can do it using / and %

so for instance, if you want to find the thousands place, the answer is


num =...
int thousands = (num / 1000) % 10

you can actually do this in a loop

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80