Consider that we wish to print a given positive integer number in words, as a sequence of digit strings. For example, number 123 should be printed as One Two Three. This might be required in financial applications, for example, to print the cheque amount in words.
We can use a loop to separate the digits of a given number and print each of them as a word using a switch statement. However, as the digits are separated from the right side (i. e., least significant digit) of a number, we need to reverse the digits of given number before this loop. The program segment that uses this approach is given below.
#include <stdio.h>
#include <math.h>
void main()
{
int rev,num;
clrscr();
printf(“Enter the number “);
scanf(“%d”, &num);
/* reverse given number num */
rev = 0;
while(num > 0)
{
rev = rev * 10 + num % 10;
num /= 10;
}
/* print number as digit strings */
while(rev > 0)
{
switch (rev % 10)
{
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;
}
rev /= 10;
}
getch();
}