Write a program that will prompt for and read a positive integer less than 1000
from the keyboard, and then create and output a string that is the value of the integer in words.
For example, if 941 is entered, the program will create the string "Nine hundred and forty one".
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <string.h>
void main(void)
{
char unit_words[][20] = {"zero", "one","two","three","four","five","six","seven","eight","nine"};
char teen_words[][20] = {"ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
char ten_words[][20] = {"error", "error","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
char hundred[] = " hundred";
char and[] = " and ";
char value_str[50] = ""; /* output string */
int value = 0; /* Integer to be converted */
int digits[] = {0,0,0}; /* Stores digits of value entered */
int i = 0;
do{
printf("Enter a positive integer less than 1000: ");
scanf("%d",&value);
}while(value<1 || value >=1000);
// get the digits of the number and store it in the digits array
while(value > 0)
{
digits[i++] = value%10;
value /= 10;
}
// checking the hundred digit
if(digits[2] > 0)
{
strcat(strcat(value_str,unit_words[digits[2]]), hundred);
if(digits[1]>0 || digits[0]>0)
strcat(value_str, and);
}
if(digits[1] > 0)
{
if(digits[1] == 1)
strcat(value_str,teen_words[digits[0]]);
else
{
strcat(value_str,ten_words[digits[1]]);
if(digits[0] > 0)
strcat(strcat(value_str, " "), unit_words[digits[0]]);
}
}
else
if(digits[0] > 0)
strcat(value_str, unit_words[digits[0]]);
printf("\n%s\n", value_str);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
UVA 10009 - All Roads Lead Where