In this blog post, we learn how to write a C program to print number in words?. We will write the C program to print numbers in words using switch cases. How to display number in words using loop in C programming. Write a C program to input a number from user and print it into words using for loop. Logic to print number in words in C programming.
Example,
Input: Input number: 2726 Output: Two Seven Two Six
Logic to print number in words:
- Ask the user to enter a positive integer number like 2724 and store it in an integer variable.
- Reverse the entered number, if you don’t know how to reverse a number, you can see the article “How to reverse a number”.
- Extract the last digit of a given number by performing modulo division by 10 and store the result in a variable.
- Now create a switch case to print digit 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
- Remove the last digit of a number
- Repeat steps 3 to 5 until the number becomes 0.
C program to print number in words:
#include <stdio.h>
#include <math.h>
int main()
{
int data, num = 0, digits;
//Ask the user to enter the number
printf("Enter any number to print in words: ");
scanf("%d", &data);
//Get all digits of entered number
digits = (int) log10(data);
//Store reverse of data in num
while(data != 0)
{
num = (num * 10) + (data % 10);
data /= 10;
}
// Find total number of trailing zeros
digits = digits - ((int) log10(num));
//Extract last digit of number and print corresponding number in words
//till num becomes 0
while(num != 0)
{
switch(num % 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;
}
num /= 10;
}
// Print all trailing 0
while(digits)
{
printf("Zero ");
digits--;
}
return 0;
}
Output:
Enter any number to print in words: 2726
Two Seven Two Six