From number to word converter
using System;
namespace ITEC102_PT1
{
public class Program
{
public static void Main(string[] args)
{
string[] first = {"Zero ", "One ", "Two ", "Three ",
"Four ", "Five ", "Six ", "Seven ",
"Eight ", "Nine ","Ten ", "Eleven ", "Twelve ",
"Thirteen ", "Fourteen ", "Fifteen ",
"Sixteen ", "Seventeen ", "Eighteen ",
"Nineteen "};
string[] tens = {"","", "Twenty ", "Thirty ", "Forty ",
"Fifty ", "Sixty ",
"Seventy ", "Eighty ", "Ninety "};
string[] hundred = {"Hundred "};
string[] thousand = {"Thousand "};
int n, x;
string result = "";
Console.WriteLine("•••NUMBER TO WORDS CONVERTER•••");
Console.WriteLine();
Console.Write("Please enter a number in the range of 0-9999 : ");
x = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine(x + " in word/s is:");
if (x >= 1000 && x <= 9999){
n = x / 1000;
result = first[n] + thousand[0];
x = x% 1000;
}if (x >= 100 && x <= 999){
n = x / 100;
result = first[n] + hundred[0];
x = x% 100;
}if (x >= 20 && x <= 99){
n = x / 10;
result = result + tens[n];
x = x%10;
}if (x >= 0 && x <= 19){
result += first[x];
}else if (x >= 10000){
Console.WriteLine("More than 4 numbers is not allowed");
}
Console.WriteLine(result);
}
}
}
Everytime that the number is ended within 100 to 9000 there’s always a zero at the end and when the number from 1000 reach 1100 the word ‘one thousand’ disappear.
Please enter a number in the range of 0-9999 : 1100
1100 in word/s is:
One Hundred Zero
I’m just a first year college student without any knowledge about coding before so please understand if I ask a basic problem. I’m still learning and want to learn more.
I apologize if there’s any mistake in my question this is my first time asking here.
Thank you
>Solution :
thats because kind of improper if-cascade, take a look on this snippet
if (x >= 1000 && x <= 9999){
n = x / 1000;
result = first[n] + thousand[0];
x = x% 1000;
}if (x >= 100 && x <= 999){
n = x / 100;
result = first[n] + hundred[0];
x = x% 100;
}
when x = 1100 then first if is executed, but on the end of this line you have x = x% 1000, so x will change and second if will be executed also. clean this cascade, make if() .. else if() .. else complete, eventually remove x = x% 1000 in these ifs, as modified x isn’t used anywhere (also n variable)
if (x >= 0 && x <= 19){
result += first[x];
}
else if (x >= 20 && x <= 99){
result = result + tens[n];
}
else if (x >= 100 && x <= 999){
result = first[n] + hundred[0];
}
else if (x >= 1000 && x <= 9999){
result = first[n] + thousand[0];
}
else if (x >= 10000){
result = "More than 4 numbers is not allowed";
}
else { // <0
result = "Negative number is not allowed";
}
Console.WriteLine(result);