Introduction
In programming, one common task is converting numerical values into their word form. This is a useful skill in applications like checks, invoices, and formal documentation. In this tutorial, we will demonstrate how to convert a number into its word representation using C++.
Objective
The objective of this program is to provide a simple and effective solution to convert any given number into its corresponding word form. Whether it’s a small number like 1 or a large number like 12345, this program will handle them all and output their word equivalents.
C++ Code
#include #include #include using namespace std; vector ones = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; vector teens = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; vector tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; vector thousands = { "", "Thousand", "Million", "Billion", "Trillion" }; string convertToWords(int num) { if (num == 0) return "Zero"; string result = ""; int idx = 0; while (num > 0) { if (num % 1000 != 0) { result = convertLessThanThousand(num % 1000) + thousands[idx] + " " + result; } num /= 1000; idx++; } return result; } string convertLessThanThousand(int num) { string result = ""; if (num >= 100) { result += ones[num / 100] + " Hundred "; num %= 100; } if (num >= 20) { result += tens[num / 10] + " "; num %= 10; } if (num >= 10) { result += teens[num - 10] + " "; } else if (num > 0) { result += ones[num] + " "; } return result; } int main() { int num; cout << "Enter a number: "; cin >> num; cout << "Number in words: " << convertToWords(num) << endl; return 0; }
Explanation of the Program
The program is structured in the following way:
- Vectors: The program defines four vectors to store words for single digits, teens, tens, and place values (thousand, million, etc.).
- convertToWords function: This is the main function that handles the conversion of a number into words. It processes the number in chunks of three digits (thousands, millions, etc.).
- convertLessThanThousand function: This function converts numbers less than 1000 into words. It first processes the hundreds, then tens, and finally ones.
- main function: It prompts the user to enter a number, calls the conversion function, and prints the resulting word form.
How to Run the Program
Follow these steps to run the program:
- Write the code in a text editor and save it with a “.cpp” extension.
- Compile the program using a C++ compiler like g++. For example, run the command:
g++ -o number_to_words number_to_words.cpp
- Run the program:
./number_to_words
- Enter a number when prompted, and the program will display the number in words.