How do I extract a single digit from a 3 digit whole number?
c, int
Solution
You can use integer division by `100`:
#include <stdio.h>
int main()
{
printf( "%d\n", 123/100 ) ;
return 0 ;
}
A more generalized approach would use subsequent rounds of modulus by `10` and integer division by `10` to remove the last digit until the number is less than `10`:
int num = 123 ;
while( num >= 10 )
{
printf( "%d\n", num % 10 ) ;
num = num / 10 ;
}
printf( "%d\n", num ) ;
If you can display your digits in reverse order from last to first this method does not require any additional storage, if not you can store the results in an array.
Problem
This isn't a homework question, I'm just curious. If I had a program that calculated a 3 digit number, say 123, how can I get just the "1"? I'm trying to print a message at the end that says "(The first digit) tells you...and (the last two digits) tell you..." But I'm not sure HOW to save or get that single digit. Any ideas? Is the a simpler way to do this other than using an array?Thanks.