C# program to print digits of a number into words

Here, we are going to learn how to print digits of a number into words in C#?
Submitted by Nidhi, on September 15, 2020

Here we will read a number from the keyboard and then print each of the numbers into words. For example, if we read a number 1234 then we will print "one two three four" on the console screen.

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.

//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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.