Friday, March 6, 2015

Number/Currency to Words Conversion

This program helps us to convert a number (<1000) into words. That is, you give 912 and it says 'nine hundred and twelve!'

Code

/* 25 February, 2015 */
/* Updated on 21 October, 2015 */

#include <stdio.h>

int main()
{
char ones[][10] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
char tenAbove[][10] = {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
char tens[][10] = {"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

int amt;

printf("Enter the amount (<10,000): ");
scanf("%d", &amt);

if(!amt)
{
printf("zero\n");
return 0;
}

if(amt/1000)
{
printf("%s thousand", ones[(amt/1000)-1]);
amt %= 1000;

if(amt) { printf(" "); }
}

if(amt/100)
{
printf("%s hundred", ones[(amt/100)-1]);
amt-=((amt/100)*100);

if(amt) { printf(" and "); }
}

if(amt/10)
{
if(((amt/10)==1) && (amt%10)) /* eleven to nineteen */
{
printf("%s\n", tenAbove[amt-11]);
return 0;
}

printf("%s", tens[(amt/10)-1]);
amt-=((amt/10)*10);

if(amt)
{
printf(" ");
}
}

if(amt)
{
printf("%s", ones[amt-1]);
}

printf("\n");

return 0;
}

Output

Enter the amount (<10,000): 1914
one thousand nine hundred and fourteen

No comments:

Post a Comment