C/Isolating digits
Expert: Zlatko - 12/7/2010
QuestionI'm looking for a way to isolate the left digit of a number i.e. 1234 = 1 OR to
successively store the right digit although I feel that would be less elegant i.e
1234 stored into a new variable as 4321, the end goal is to have numbers
print as words as does this program... backwards.
#include <stdio.h>
int main (void)
{
int number, right_digit;
printf ("Enter your number
");
scanf ("%i", &number);
do {
right_digit = number % 10;
number = number / 10;
if (right_digit == 0)
printf("zero ");
if (right_digit == 1)
printf("one ");
if (right_digit == 2)
printf("two ");
if (right_digit == 3)
printf("three ");
if (right_digit == 4)
printf("four ");
if (right_digit == 5)
printf("five ");
if (right_digit == 6)
printf("six ");
if (right_digit == 7)
printf("seven ");
if (right_digit == 8)
printf("eight ");
if (right_digit == 9)
printf("nine ");
}
while (number != 0);
printf ("
");
return 0;
}
Help greatly appreciated,
Clifton
AnswerHello Clifton
Here is another way using a lookup array, and some floating point routines to get the leftmost digits.
#include <stdio.h>
#include <math.h>
const char* digitText[] =
{
"zero ",
"one ",
"two ",
"three ",
"four ",
"five ",
"six ",
"seven ",
"eight ",
"nine "
};
int main (void)
{
while (1)
{
int number;
int magnitude;
int left_digit;
printf ("Enter your number ");
// use %d, not %i. %i will interpret 0123 as octal 123
scanf ("%d", &number);
magnitude = (int)pow(10, floor(log10(number)));
if (magnitude == 0)
{
printf("%s", digitText[number]);
}
else while(magnitude > 0)
{
left_digit = (number / magnitude) % 10;
magnitude /= 10;
printf("%s", digitText[left_digit]);
}
printf ("\n");
}
return 0;
}