Thread: How to modulo to this digit

1. 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.

2. %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

3. 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?

4. 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?

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

6. 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.

7. Thanks, that works. Can you please explain what I was doing wrong and how your way worked?

8. 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

9. Oh, now I understand... Thanks again!

10. Very good!

11. Correction:
Code:
```while (num > 9)    /* not 10 */
num /= 10;

return num;```

12. Ack! A bug!!

Yes, thank you, nonoob! Make that change, C-Man, if you haven't already.

13. For the rest of the class...
Problem is exacerbated with input number whose digits start with 10... The result would yield 10.