C Program to Convert Number to Words

In this tutorial, we will create a C program to Convert Numbers to Words.

Consider a number 278 is taken as an input, now the program will convert this numeric value to words such as “Two Hundred Seventy Eight”. We have to create a program keeping the place values in minds such as ones, tens, hundreds, etc.

Example:

Input: 147
Output: One Hundred Forty-Seven.


C program to Print Number in Words

The following program handles the integer between 0 to 9999.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//Function
void convertFunc(char *num)
{
  int len = strlen(num);

  // checking cases for the length of the number
  if (len == 0)
  {
    fprintf(stderr, "empty string\n");
    return;
  }

  if (len > 4)
  {
    fprintf(stderr, "Length more than 4 is not supported\n");
    return;
  }

  //The first string is not used, it is to make array indexing simple
  char *single_digit[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

  //The first two string are not used, they are to make array indexing simple
  char *tens_place[] = { "", "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" };

  // Used for debugging purpose only
  printf("\n%s: ", num);

  // used for single digit number
  if (len == 1)
  {
    printf("%s\n", single_digit[*num - '0']);
    return;
  }

  // Iteration
  while (*num != '\0')
  {
    //first 2 digits
    if (len >= 3)
    {
      if (*num - '0' != 0)
      {
        printf("%s ", single_digit[*num - '0']);
        printf("%s ", tens_power[len - 3]);
      }

      --len;
    }

    // last 2 digits
    else
    {
      // Need to explicitly handle 10-19. Sum of the two digits is
      //used as index of "tens_place" array of strings
      if (*num == '1')
      {
        int sum = *num - '0' + *(num + 1) - '0';
        printf("%s\n", tens_place[sum]);
        return;
      }

      //explicitely handle 20
      else if (*num == '2' && *(num + 1) == '0')
      {
        printf("twenty\n");
        return;
      }

      // Rest of the two digit numbers i.e., 21 to 99
      else
      {
        int i = *num - '0';
        printf("%s ", i ? tens_multiple[i] : "");
        ++num;
        if (*num != '0')
          printf("%s ", single_digit[*num - '0']);
      }
    }

    ++num;
  }
}

//main function
int main()
{
  //calling function with different inputs
  convertFunc("123");
  convertFunc("5648");
  convertFunc("336");

  return 0;
}

Output:

123: one hundred twenty three
5648: five thousand six hundred forty eight
336: three hundred thirty six