text: Program to convert a given number to words | C program to print a given number in words . The program handles numbers from 0 to 9999 ; A function that prints given number in words ; Base cases ; The first string is not used , it is to make array indexing simple ; The first string is not used , it is to make array indexing simple ; The first two string are not used , they are to make array indexing simple ; Used for debugging purpose only ; For single digit number ; Iterate while num is not ' \0' ; Code path for first 2 digits ; tens_power [ len - 3 ] ) ; here len can be 3 or 4 ; Code path for last 2 digits ; Need to explicitly handle 10 - 19. Sum of the two digits is used as index of " two _ digits " array of strings ; Need to explicitely handle 20 ; Rest of the two digit numbers i . e . , 21 to 99 ; Driver program to test above function
code: #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE void convert_to_words ( char * num ) { int len = strlen ( if ( len == 0 ) { fprintf ( stderr , " empty ▁ string STRNEWLINE " ) ; return ; } if ( len > 4 ) { fprintf ( stderr , " Length ▁ more ▁ than ▁ 4 ▁ is ▁ not ▁ supported STRNEWLINE " ) ; 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 ( " % s : " , num ) ; if ( len == 1 ) { printf ( " % s STRNEWLINE " , single_digits [ * num - '0' ] ) ; return ; } while ( * num != ' \0' ) { if ( len >= 3 ) { if ( * num - '0' != 0 ) { printf ( " % s ▁ " , single_digits [ * num - '0' ] ) ; printf ( " % s ▁ " , } -- len ; } else { if ( * num == '1' ) { int sum = * num - '0' + * ( num + 1 ) - '0' ; printf ( " % s STRNEWLINE " , two_digits [ sum ] ) ; return ; } else if ( * num == '2' && * ( num + 1 ) == '0' ) { printf ( " twenty STRNEWLINE " ) ; 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 ) { convert_to_words ( "9923" ) ; convert_to_words ( "523" ) ; convert_to_words ( "89" ) ; convert_to_words ( "8" ) ; return 0 ; }