C++ Program to Print Number in Characters
This program in C++ helps in printing out any given number in characters.
Syntax
#include<iostream>
using namespace std;
int main() {
// variable declaration
int n, digit;
// array declaration
char numbers[10][10] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
// user input
cout << "Enter number: ";
cin >> n;
// converting number to words
cout << "The number in words is: ";
while (n > 0) {
digit = n % 10;
n /= 10;
cout << numbers[digit] << " ";
}
return 0;
}
Example
Let's say we want to print out the number "3584" in characters. Using the above program, the output would be:
Enter a number: 3584
The number in words is: Four Eight Five Three
Explanation
In this program, we first declare an integer variable "n" to hold the value of the number entered by the user and an integer variable "digit" to hold the value of each digit in the number.
Next, we declare a two-dimensional array of characters called "numbers" and initialize it with the names of each number from 0 to 9.
We then prompt the user to enter a number and store it in the variable "n". Using a while loop, we extract each digit from the number one by one using the modulus operator and convert it to its corresponding word from the "numbers" array. We then print out each word, separated by a space.
Use
This program can be used to convert any given number into its corresponding words. It can be useful in scenarios where you need to display a number in words, such as in a check writing application or a number-to-word converter program.
Important Points
- This program uses an array of character strings to hold the number names.
- It uses a while loop to convert each digit of the number to its corresponding word.
- The program prints out the words separated by a space.
Summary
In summary, this C++ program converts any given number to its corresponding words using a two-dimensional array of character strings to hold the number names and a while loop to extract each digit from the number and convert it to its corresponding word. This program can be useful in scenarios where you need to display a number in words, such as in a check writing application or a number-to-word converter program.