Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop not producing correct results

Tags:

c#

while-loop

I am trying to use a while-loop to ask the user for a number between 1 and 10. While the user fails to enter a number between 1 and 10 (inclusive), I want to ask them for another number.

My code so far is:

int i = 0;
Console.WriteLine("Enter a number.");
while (i <= 10)
{
    Console.ReadLine();

    if (i > 1 && i < 10)
    {
        Console.ReadLine();
        continue;
    }

    if (i < 1 && i > 10)
    {
        Console.WriteLine("Enter New Number...");
        break;
    }

    Console.ReadLine();
}

What am I doing wrong?

like image 794
Saisano Avatar asked Dec 31 '25 07:12

Saisano


2 Answers

You're writing if (i < 1 && i > 10).
i can never be both less than 1 and more than 10.
(Hint: 'and' is the wrong word)

Also, you never assigned a value to i.
(Hint: call int.Parse)

Also, you probably want to swap break (which stops looping) and continue (which continues looping)

Also, what should the condition in the while loop be?

like image 168
SLaks Avatar answered Jan 01 '26 20:01

SLaks


int i = 0;
while (i < 1 || i > 10)
{
    int.TryParse(Console.ReadLine(),out i);
}

or with text

int i = 0;
Console.WriteLine("Enter a number");
int.TryParse(Console.ReadLine(),out i);
while (i < 1 || i > 10)
{
    Console.WriteLine("Try Again");
    int.TryParse(Console.ReadLine(),out i);
}

:)

like image 40
Paul Creasey Avatar answered Jan 01 '26 21:01

Paul Creasey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!