C Program for Converting digit/number to words

Converting Digits/ Numbers in words in C

Here, in this page we will discuss the program for numbers in words in C .The conversion of numbers in words is just a conversion of numeric values to English format of reading numbers. This code supports the conversion of numbers from 0-9999 in English Format. Digits have different places when read from it’s once place to above. Different places for numbers are :

  • Single digits:- Ones
  • Two Digits:-Tens
  • Three Digits:- Hundreds
  • Four Digits:- Thousands

Etc. as in this program we will be converting only upto 4 digits

numbers in words in C

Algorithm

  • Step 1:- Start.
  • Step 2:- Taking input as a string from the user.
  • step 3:- Check the length of the input.
  • step 4:- if the length is zero print ’empty’ and if the length is greater than 4 print ‘give a string of specific length’
  • Step 5:- if length id between 1 – 4, Create arrays for different values.
  • Step 6:- Checking the length of the string.
  • Step 7:- According to the place of the digit, we will show the output.
  • Step 8:- End.
Python Program for converting numbers/digits in words

Code in C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void convert_to_words(char *num)
{
  int len = strlen(num); 
  if (len == 0)
  {
    fprintf(stderr, "empty string\n");
    return;
  }
  if (len > 4) 
  {
    fprintf(stderr, "Length more than 4 is not supported\n");
    return;
  }
  char *single_digits[] = { "zero", "one", "two", "three", "four","five", "six", "seven", "eight", "nine"};
  char *two_digits[] = {"", "ten", "eleven", "twelve", "thirteen", "fourteen","fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
  char *tens_multiple[] = {"", "", "twenty", "thirty", "forty", "fifty","sixty", "seventy", "eighty", "ninety"};
  char *tens_power[] = {"hundred", "thousand"};
  printf("\n%s: ", num);
  if (len == 1) 
  {
    printf("%s\n", single_digits[*num - '0']);
    return;
  }
  while (*num != '\0') 
  {
    if (len >= 3) 
    {
      if (*num -'0' != 0) 
      {
        printf("%s ", single_digits[*num - '0']);
        printf("%s ", tens_power[len-3]); 
      }
      --len;
    }
    else 
    {
      if (*num == '1') 
      {
        int sum = *num - '0' + *(num + 1)- '0';
        printf("%s\n", two_digits[sum]);
        return;
      }
      else if (*num == '2' && *(num + 1) == '0') 
      {
        printf("twenty\n");
        return;
      }
      else 
      {
        int i = *num - '0';
        printf("%s ", i? tens_multiple[i]: "");
        ++num;
        if (*num != '0')
          printf("%s ", single_digits[*num - '0']);
      }
    }
    ++num;
  }
}
int main(void)
{
  char num[4];
  scanf("%s",num);
  convert_to_words(num);
  return 0;
}
Output:
1121 : one thousand one hundred twenty one

Comments