Program to Convert Digit/Number to Words in C++

Converting Numbers to Words

Converting a number to words is a common problem in programming.

We will explore three different methods to achieve this in C++.

Method 1: Using Arrays

This method utilizes arrays to map digits to their word equivalents.

#include <iostream>
using namespace std;

void convertToWords(int num) {
    string single_digits[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    cout << single_digits[num];
}

int main() {
    int num;
    cout << "Enter a single-digit number: ";
    cin >> num;
    if (num >= 0 && num <= 9)
        convertToWords(num);
    else
        cout << "Invalid input!";
    return 0;
}
            
Input: 5
Output: Five

Method 2: Using String Manipulation

This method handles multi-digit numbers using a loop.

#include <iostream>
#include <string>
using namespace std;

void convertToWords(int num) {
    string single_digits[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    string str = to_string(num);
    for (char ch : str) {
        cout << single_digits[ch - '0'] << " ";
    }
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    convertToWords(num);
    return 0;
}
            
Input: 123
Output: One Two Three

Method 3: Using Recursion

This method recursively processes each digit.

#include <iostream>
using namespace std;

string single_digits[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};

void convertToWordsRecursive(int num) {
    if (num == 0)
        return;
    convertToWordsRecursive(num / 10);
    cout << single_digits[num % 10] << " ";
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    if (num == 0)
        cout << "Zero";
    else
        convertToWordsRecursive(num);
    return 0;
}
            
Input: 507
Output: Five Zero Seven
Numbers

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

HCF - Highest Common Factor: C C++ Java Python

LCM - Lowest Common Multiple: C C++ Java Python

GCD - Greatest Common Divisor: C C++ Java Python

Binary to Decimal Conversion: C C++ Java Python

Octal to Decimal Conversion: C C++ Java Python

Hexadecimal to Decimal Conversion: C C++ Java Python

Decimal to Binary Conversion: C C++ Java Python

Decimal to Octal Conversion: C C++ Java Python

Decimal to Hexadecimal Conversion: C C++ Java Python

Binary to Octal Conversion: C C++ Java Python

Quadrants in which a given coordinate lies: C C++ Java Python

Addition of Two Fractions: C C++ Java Python

Calculate the Area of a Circle: C C++ Java Python

Convert Digit/Number to Words: C C++ Java Python

Finding Roots of a Quadratic Equation: C C++ Java Python