C# - Write a number in Words
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConvertNumberToWords
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter
the number which needs to be spelled out and hit ENTER Key : ");
int num = Convert.ToInt32(Console.ReadLine());
NumberToWordCoversion numword = new NumberToWordCoversion();
string convertedstring = numword.Conversion(num);
Console.WriteLine(convertedstring);
Console.ReadLine();
}
}
class NumberToWordCoversion
{
public string
Conversion(int number)
{
int[] n = new int[100];
string
final = "";
int actualarrayfilled =0;
string[] words = new string[10]{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
while(number >= 1)
{
n[actualarrayfilled] = number % 10;
number = number / 10;
actualarrayfilled++;
}
for (int j =
actualarrayfilled-1; j >= 0; j--)
{
final = final + words[n[j]] + " ";
}
return(final);
}
}
}
Output :
Alternate method using Switch Case :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConvertNumberToWords
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter
the number which needs to be spelled out and hit ENTER Key : ");
int num = Convert.ToInt32(Console.ReadLine());
NumberToWordCoversion numword = new NumberToWordCoversion();
string convertedstring =
numword.Conversion(num);
Console.WriteLine(convertedstring);
Console.ReadLine();
}
}
class NumberToWordCoversion
{
public string
Conversion(int number)
{
int[] n = new int[100];
string final = "";
int actualarrayfilled =0;
//string[] words = new
string[10]{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
while(number >= 1)
{
n[actualarrayfilled] = number % 10;
number = number / 10;
actualarrayfilled++;
}
for (int j =
actualarrayfilled-1; j >= 0; j--)
{
//
final = final + words[n[j]] + " ";
switch (n[j])
{
case 0:
final = final + "Zero" + "
";
break;
case 1:
final = final + "One" + "
";
break;
case 2:
final = final + "Two" + "
";
break;
case 3:
final = final + "Three" + "
";
break;
case 4:
final = final + "Four" + "
";
break;
case 5:
final = final + "Five" + "
";
break;
case 6:
final = final + "Six" + "
";
break;
case 7:
final = final + "Seven" + "
";
break;
case 8:
final = final + "Eight" + "
";
break;
case 9:
final = final + "Nine" + "
";
break;
default:
final = "";
break;
}
}
return(final);
}
}
}
Output:
No comments:
Post a Comment