# How to modulo to this digit

• 02-17-2011
.C-Man.
How to modulo to this digit
If I enter this input (number): 52483
(let's call the input 'num')

how can I modulo to get the '5'?

I know to get the 3, I only need to do num % 10, but how do I modulo to get the '5'?

also, I need something that will work if the number is longer or shorter than this input (For example if num were '2342' or longer '1290381' how would I modulo to get the number all the way at the left?)

Thanks.
• 02-17-2011
Salem
%10 gets you the right most digit
/10 drops the right most digit

Do them both in a loop, and you'll get each digit in turn, reading R->L
• 02-17-2011
.C-Man.
I've tried while(num != 0) and then what you said... but then it prints 0 for the most left digit... do you know what i'm doing wrong?
• 02-17-2011
while(number > 0) is better, imo.

Post your code so we can see just what you're doing. You're modulo'ing first by ten, and then dividing by ten, right?
• 02-17-2011
.C-Man.
Code:

```while(num > 0) {                 num / 10;                 num % 10;                 mostSig == num;         }```
it doesn't print anything now... the output just goes blank.
• 02-17-2011
Code:

```while(num > 9) { //>10 is a bug!   n = num % 10;                  num =num / 10;   printf("I removed the digit %d  Number is now: %d\n", n, num);                } printf("Most significant digit is: %d \n", num);```
Try that.
• 02-17-2011
.C-Man.
Thanks, that works. Can you please explain what I was doing wrong and how your way worked?
• 02-17-2011
First, the num > 9 had to be changed from num > 0, because you weren't peeling off all the digits. You wanted to keep the left most digit.

When you do an operation like multiply divide, modulo, etc., you have to have a variable to "catch" the result: num / 10, doesn't catch the result of the division. The answer flies right by and into the night.

You needed to modulo the number FIRST, and then divide it.

A common and useful abbreviated idiom in C is: num /= 10, which is exactly the same as the more verbose: num = num /10. Works for all the basic arithmetic operations: num += 5, etc.

You're welcome :D
• 02-17-2011
.C-Man.
Oh, now I understand... Thanks again! :D
• 02-17-2011
Very good! :D
• 02-17-2011
nonoob
Correction:
Code:

```while (num > 9)    /* not 10 */     num /= 10; return num;```
• 02-17-2011