Write a C program to input a number from user and print it into words using for loop. How to display number in words using loop in C programming. Logic to print number in words in C programming.
Input number: 1234
One Two Three Four
Required knowledge
Logic of convert number in words
- Input number from user. Store it in some variable say num.
- Extract last digit of given number by performing modulo division by 10. Store the result in a variable say
digit = num % 10. - Switch the value of digit found above. Since there are 10 possible values of digit i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 hence, write 10 cases. Print corresponding word for each
case. - Remove last digit from num by dividing it by 10 i.e.
num = num / 10. - Repeat step 2 to 4 till number becomes 0.
/**
* C program to print number in words
*/
#include <stdio.h>
int main()
{
int n, num = 0;
/* Input number from user */
printf("Enter any number to print in words: ");
scanf("%d", &n);
/* Store reverse of n in num */
while(n != 0)
{
num = (num * 10) + (n % 10);
n /= 10;
}
/*
* Extract last digit of number and print corresponding digit 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 = num / 10;
}
return 0;
}Program to display number in words
/**
* C program to display number in words
*/
#include <stdio.h>
#include <math.h>
int main()
{
int n, num = 0, digits;
/* Input number from user */
printf("Enter any number to print in words: ");
scanf("%d", &n);
/* Find total digits in n */
digits = (int) log10(n);
/* Store reverse of n in num */
while(n != 0)
{
num = (num * 10) + (n % 10);
n /= 10;
}
/* Find total 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 zeros */
while(digits)
{
printf("Zero ");
digits--;
}
return 0;
}
Comments
Post a Comment