fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. void convert_to_words(char *num)
  6. {
  7. int len = strlen(num);
  8.  
  9. char *single_digits[] = { "zero", "one", "two", "three", "four",
  10. "five", "six", "seven", "eight", "nine"};
  11.  
  12.  
  13. char *two_digits[] = {"", "ten", "eleven", "twelve", "thirteen", "fourteen",
  14. "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
  15.  
  16.  
  17. char *tens_multiple[] = {"", "", "twenty", "thirty", "forty", "fifty",
  18. "sixty", "seventy", "eighty", "ninety"};
  19.  
  20. char *tens_power[] = {"hundred", "thousand"};
  21.  
  22. /* Used for debugging purpose only */
  23. printf("\n%s: ", num);
  24.  
  25. /* For single digit number */
  26. if (len == 1) {
  27. printf("%s\n", single_digits[*num - '0']);
  28. return;
  29. }
  30.  
  31. /* Iterate while num is not '\0' */
  32. while (*num != '\0') {
  33.  
  34. /* Code path for first 2 digits */
  35. if (len >= 3) {
  36. if (*num -'0' != 0) {
  37. printf("%s ", single_digits[*num - '0']);
  38. printf("%s ", tens_power[len-3]); // here len can be 3 or 4
  39. }
  40. --len;
  41. }
  42.  
  43. /* Code path for last 2 digits */
  44. else {
  45. /* Need to explicitly handle 10-19. Sum of the two digits is
  46.   used as index of "two_digits" array of strings */
  47. if (*num == '1') {
  48. int sum = *num - '0' + *(num + 1)- '0';
  49. printf("%s\n", two_digits[sum]);
  50. return;
  51. }
  52.  
  53. /* Need to explicitely handle 20 */
  54. else if (*num == '2' && *(num + 1) == '0') {
  55. printf("twenty\n");
  56. return;
  57. }
  58.  
  59. /* Rest of the two digit numbers i.e., 21 to 99 */
  60. else {
  61. int i = *num - '0';
  62. printf("%s ", i? tens_multiple[i]: "");
  63. ++num;
  64. if (*num != '0')
  65. printf("%s ", single_digits[*num - '0']);
  66. }
  67. }
  68. ++num;
  69. }
  70. }
  71.  
  72. /* Driver program to test above function */
  73. int main(void)
  74. {
  75. convert_to_words("9923");
  76. convert_to_words("523");
  77. convert_to_words("89");
  78. convert_to_words("8989");
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
9923: nine thousand nine hundred twenty three 
523: five hundred twenty three 
89: eighty nine 
8989: eight thousand nine hundred eighty nine