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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | #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