Alexander C.
Alexander C.

Reputation: 1181

For loop and If statement

int i;
int[] mArray = new int[5];

for (i = 0; i < mArray.Length; i++)
{
    Console.WriteLine("Please enter a number:");
    mArray[i] = Convert.ToInt32(Console.ReadLine());

    if (mArray[i] >= 50 && mArray[i] <= 10)
    {
        Console.WriteLine("Please enter numbers only between 10 and 50.");
        mArray[i] = Convert.ToInt32(Console.ReadLine());
    }

}

Can't seem to get if statement to work when it has two rules in it if (mArray[i] >= 50 && mArray[i] <= 10)

But it works fine with 1 rule if (mArray[i] >= 50)

Upvotes: 1

Views: 191

Answers (7)

Tomtom
Tomtom

Reputation: 9394

Which number is bigger than 50 AND in the same moment smaller then 10? I think you should replace your && (AND) with || (OR)

Upvotes: 4

Dutts
Dutts

Reputation: 6191

Try changing your logic to:

if (mArray[i] >= 50 || mArray[i] <= 10)

Upvotes: 2

Tigran
Tigran

Reputation: 62248

It depends on how you intend to make it work

/*Pass if the value is more or equal 50 OR lesst or equal 10*/
mArray[i] >= 50 || mArray[i] <= 10 

or

/*Passs if the value is between 10 and 50, including edges*/
mArray[i] >= 10 && mArray[i] <= 50 

Upvotes: 3

Kyborek
Kyborek

Reputation: 1511

No number can be larger than 50 AND smaller than 10, your condition is wrong:

if (mArray[i] >= 50 && mArray[i] <= 10)

it should be

if (mArray[i] >= 50 || mArray[i] <= 10)

Upvotes: 3

Nolonar
Nolonar

Reputation: 6122

Your statement is impossible. myArray[i] has to be both larger than 50 AND smaller than 10. Did you mean:

if (mArray[i] >= 50 || mArray[i] <= 10)

?

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500105

Look at your condition:

if (mArray[i] >= 50 && mArray[i] <= 10)

You're trying to find a number which is simultaneously at least 50 and at most 10.

What number did you have in mind that would be considered invalid?

I suspect you meant:

if (mArray[i] > 50 || mArray[i] < 10)

Note that I've changed >= and <= to > and < respectively to match your message - I assume you want 10 or 50 to be valid.

Also note that you're only testing for validity once - if the user persists in entering a second bad number, you'll accept that. I suspect you want something like:

Console.WriteLine("Please enter a number:");
int value = Convert.ToInt32(ConsoleReadLine());

while (value > 50 || value < 10)
{
    Console.WriteLine("Please enter numbers only between 10 and 50.");
    value = Convert.ToInt32(Console.ReadLine());
}
// Now we know it's valid, so it's reasonably to put it in the array
mArray[i] = value;

Upvotes: 4

cuongle
cuongle

Reputation: 75306

You should use || instead of &&

mArray[i] >= 50 || mArray[i] <= 10 

Upvotes: 5

Related Questions