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