Answer: Find the place value of the first digit (\(10^{d-1}\) for a \(d\)-digit number), then take digits from the left with / and %, printing the word for each digit with a switch.
Logic
- If the number is 0, print Zero and stop.
- Find div = place value of the leftmost digit (for 1203, div = 1000).
- Repeat while div > 0: digit = num / div; print its word; num = num % div; div = div / 10.
- Taking digits from the left keeps every zero, so 1203 and 100 come out correctly. (Reversing the number first, as some versions do, loses zeros at the end: 120 reversed is 21.)
Program
#include <stdio.h>
void printDigit(int digit);
int main()
{
int num, temp, div = 1;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
if (num == 0) {
printDigit(0);
printf("\n");
return 0;
}
/* div = 10^(number of digits - 1), e.g. 1203 -> 1000 */
temp = num;
while (temp >= 10) {
div = div * 10;
temp = temp / 10;
}
/* take digits from the left, so zeros are not lost */
while (div > 0) {
printDigit(num / div);
num = num % div;
div = div / 10;
}
printf("\n");
return 0;
}
void printDigit(int digit)
{
switch (digit) {
case 0: printf("Zero "); break;
case 1: printf("One "); break;
case 2: printf("Two "); break;
case 3: printf("Three "); break;
case 4: printf("Four "); break;
case 5: printf("Five "); break;
case 6: printf("Six "); break;
case 7: printf("Seven "); break;
case 8: printf("Eight "); break;
case 9: printf("Nine "); break;
}
}Sample runs (gcc)
Enter a non-negative integer: 1203
One Two Zero Three
Enter a non-negative integer: 100
One Zero Zero
Enter a non-negative integer: 0
Zero