The source code to print digits of a number into words is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to print a number in words.
using System;
public class Demo
{
static void PrintWords(int num)
{
string[] words = { "zero", "one", "two",
"three", "four", "five",
"six", "seven", "eight",
"nine" };
int digit = 0;
int i = 0;
int j = 0;
int[] digit_array= new int[10];
while (num > 0)
{
digit = num % 10;
digit_array[i++] = digit;
num = num / 10;
}
for (j = i - 1; j >= 0; j--)
{
Console.Write(words[digit_array[j]] + " ");
}
Console.WriteLine();
}
static void Main()
{
int num;
Console.Write("Enter the number: ");
num = int.Parse(Console.ReadLine());
Console.WriteLine("Number in words: ");
PrintWords(num);
}
}
Output:
Enter the number: 2363
Number in words:
two three six three
Press any key to continue . . .
Explanation:
In the above program, we created a class Demo that contains two static methods PrintWords() and Main().
The PrintWords() method print the words for each digit of a specified integer number, here we declared an array that contains the words for each digit from 0 to 9 then we find the digits of a number after divide by 10 and store into an array, and then print the words for each digit on the console screen.
In the Main() method, we read the value of the number from the keyboard and pass to the method PrintWords(), because the Main() method is the entry point of the program.
Program:
The source code to print digits of a number into words is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class Demo that contains two static methods PrintWords() and Main().
The PrintWords() method print the words for each digit of a specified integer number, here we declared an array that contains the words for each digit from 0 to 9 then we find the digits of a number after divide by 10 and store into an array, and then print the words for each digit on the console screen.
In the Main() method, we read the value of the number from the keyboard and pass to the method PrintWords(), because the Main() method is the entry point of the program.