Search code examples
c#console-applicationuniqueuser-input

Write a program in C# and ask the user to enter 5 unique numbers


Write a program and ask the user to enter 5 numbers. If a number has been previously entered, display an error message and ask the user to retry. Once the user successfully enters 5 unique numbers, sort them and display the result on the console.

Can anybody please help me on this one? I'm really confused on how to solve this. Here's my code:

var number = new int[5];
Console.WriteLine("Enter 5 unique numbers");

for (int i = 0; i < 5; i++)
{
    number[i] = Convert.ToInt32(Console.ReadLine());
    var numberValue = number[i];

    var currentNumber = Array.IndexOf(number, numberValue);
    if (number[i] == number[0])
    {
        continue;
    }
    else
    {
        if (!(currentNumber == number[i]))
        {
            continue;
        }
        else
        {
            Console.WriteLine("Hold on, you already entered that number. Try again.");
        }
    }

    /* foreach (var n in number) { ... } */
    continue;
}

Array.Sort(number);
Console.WriteLine();

foreach (var n in number)
    Console.WriteLine(n);

Console.WriteLine();

I can't find the solution on the checking if there is already the same number input. Help me please. And please explain why it is the answer.

PS: Can you please only use simple code and do not use keywords like HashSet? I know that will solve the problem but I don't know it yet. I'm just trying to learn C# step by step so I'm sorry for that.. Thank you!


Solution

  •         var number = new int[5];
            Console.WriteLine("Enter 5 unique numbers");
    
            for (int i = 0; i < 5; i++)
            {
                while (true)
                {
                    var newValue = Convert.ToInt32(Console.ReadLine());
                    var currentNumber = Array.IndexOf(number, newValue);
                    if (currentNumber == -1)
                    {
                        number[i] = newValue; // Accept New value
                        break;
                    }
                    Console.WriteLine("Hold on, you already entered that number. Try again.");
                }
            }
    
            Array.Sort(number);
            Console.WriteLine();
    
            foreach (var n in number)
                Console.WriteLine(n);
    
            Console.ReadLine();
    

    Array.IndexOf() returns index of numberValue in array, or -1 if it does not exist.