C program to convert number in word

In this program, you will take integer input from users and you will convert the integer into a word. For example, you will take input 1234, the output will be one two three four.

#include<stdio.h>
int main()
{
    long int n=0,rev=0,rmd,i=0;
    printf("enter the number:");
    scanf("%d",&n);
    while(n!=0)
    {
    rmd=n%10;
    n/=10;
    i+=1;
    rev=rev*10+rmd;
    }
    while(i)
    {
        rmd=0;
        rmd=rev%10;
        rev=rev/10; 
        i--;
        printf(" ");
        switch(rmd)
        {
            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;
        }
    }
    return 0;
}

output

enter the number:1000
one zero zero zero

Working of numbers to word conversion

  • In this program, you will take integer input from the user and store it in a variable n.
  • In the outer while loop, you will reverse the number and store it in variable rev i.e rev=rev*10+rmd, and count the number of digits in an input number by incrementing the value of i
  • For example, if the user enters the number 123 then after reversing the number, the number becomes 321 and i value becomes 3.
  • in the inner while loop, you will find a reminder of the rev number.
  •  in the first iteration, when i=3 you will find a reminder of the rev number and stored reminder in variable rmd i.e reminder of 321 is 1, divide rev=rev/10 and rev become 32, now you will pass rmd i.e 1 in the switch case, in the switch case, case 1 will get executed and 'one' will get printed.
  • when i=2, a reminder of 32 is 2, divide rev=rev/10 and rev become 3,  now you will pass rmd i.e 2 in the switch case, in the switch case, case 2 will get executed and 'two' will get printed.
  • when i=1, a reminder of 3 is 3, divide rev=rev/10 and rev become 0, now you will pass rmd i.e 3 in the switch case, in the switch case, case 3 will get executed and 'three' will get printed.
    when i=0, while loop gets a break.

Dry run of numbers to a word conversion program

input i.e n=123
in outer while loop
rmd=3 , n=12  rev=3,   i=1
rmd=2, n=1 rev=32,  i=2
rmd=1, n=0,  rev=321, i=3

in inner while loop,
reminder of rev i.e 321
rev=321
i=3, rev=321, rmd=1 print 'one'
i=2, rev=32, rmd=2 print 'two'
i=1, rev=3, rmd=3 print 'three'

input:123
output: one two three