Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program to convert a given number to words
In C programming, converting numbers to words is a common problem that involves breaking down a number into its place values and mapping each digit to its corresponding word representation. This program converts numbers from 0 to 9999 into their English word equivalents.
Syntax
void convert(char *num);
Algorithm Overview
The conversion process involves these key steps −
- Parse the input string to determine its length
- Use arrays to store word representations for different place values
- Process digits from left to right based on their position
- Handle special cases for numbers 10-19 and multiples of 10
Example
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void convert(char *num) {
int len = strlen(num);
if (len == 0) {
fprintf(stderr, "empty string
");
return;
}
if (len > 4) {
fprintf(stderr, "Length more than 4 is not supported
");
return;
}
char *single_digit[] = {"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
char *tens_place[] = {"", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"};
char *tens_multiple[] = {"", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};
char *tens_power[] = {"hundred", "thousand"};
printf("%s: ", num);
if (len == 1) {
printf("%s
", single_digit[*num - '0']);
return;
}
while (*num != '\0') {
if (len >= 3) {
if (*num - '0' != 0) {
printf("%s ", single_digit[*num - '0']);
printf("%s ", tens_power[len-3]);
}
--len;
}
else {
if (*num == '1') {
int sum = *num - '0' + *(num + 1) - '0';
printf("%s
", tens_place[sum]);
return;
}
else if (*num == '2' && *(num + 1) == '0') {
printf("twenty
");
return;
}
else {
int i = *num - '0';
printf("%s ", i ? tens_multiple[i] : "");
++num;
if (*num != '0')
printf("%s", single_digit[*num - '0']);
printf("
");
return;
}
}
++num;
}
}
int main() {
convert("1234");
convert("567");
convert("89");
convert("5");
return 0;
}
1234: one thousand two hundred thirty four 567: five hundred sixty seven 89: eighty nine 5: five
Key Points
- The program handles numbers from 0 to 9999 using string input
- Special handling is required for numbers 10-19 and multiples of 10
- Arrays store word mappings for efficient lookup by index
- The algorithm processes digits based on their positional value
Conclusion
This number-to-words converter demonstrates string manipulation and array usage in C. It efficiently handles place values and special cases to produce accurate word representations of numeric inputs up to four digits.
Advertisements
