You are here:

C/Isolating digits

Advertisement


Question
I'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

Answer
Hello 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;
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.