RandomPerson
RandomPerson

Reputation: 790

While loop not properly checking all conditions?

So the assignment is as follows: you can enter all sorts of numbers but when you enter 0 two times in a row it needs to stop. The first time you enter a number your not allowed to enter 0.

This is the code I have setup:

class MainClass
{
    public static void Main (string[] args)
    {
        int givenNumber, prevNumber;
        Console.WriteLine ("Enter a number: ");
        int.TryParse (Console.ReadLine (), out givenNumber);
        // I've set the prevNumber to givenNumber because the variable has to be initialized
        // before I can use it in the condition below. I thought setting it to the giveNumber
        // wouldn't harm. Note that the first time your not allowed to enter 0
        prevNumber = givenNumber;
        while (givenNumber != 0 && prevNumber != 0) {
            prevNumber = givenNumber; //Here is where they both are 0 at a given moment, but only after the condition.
            Console.WriteLine ("Enter a number: ");
            int.TryParse (Console.ReadLine (), out givenNumber);
        }
        Console.WriteLine ("Tada");
    }
}

The problem is that it already stops when you've only entered one 0. For example if I'd first enter a 7 to start with, and my next number would be 0. When I debug it it says that my givenNumber is 0 and prevNumber is 7, when it goes back to the while condition it stops and finishes. When the program finishes the debug clearly says prevNumber = 7 and givenNumber = 0. I am using the conditional AND correct am I not?

Any clue? I'm not allowed to use arrays for this matter.

Thanks in advance

Upvotes: 4

Views: 139

Answers (3)

RBarryYoung
RBarryYoung

Reputation: 56725

Ooh, right, you've got the logic wrong. It should be this:

while ((givenNumber != 0) || (prevNumber != 0)) {

Look up DeMorgan's laws to see why...

Upvotes: 2

user3784270
user3784270

Reputation: 11

Your problem is with your conditional statement.

Right now you're checking whether both the givenNumber and the PrevNumber DO NOT equal 0.

So, if neither of them equals 0 then the statement will evaluate to TRUE. However, if either one of the numbers is 0 then the statement will evaluate to FALSE, since (TRUE) && (FALSE) evaluates to FALSE.

There are two ways to fix this: You can either use || (the "OR" operator) with the two "!=" statements, or you can negate the whole thing and use regular equality rather than "!=" as such: !(givenNumber == 0 && prevNumber == 0)

Upvotes: 1

user2126375
user2126375

Reputation: 1614

while (givenNumber != 0 && prevNumber != 0)

For first read value from console - number 7 givenNumer will be 7 prevNumber will be 7 too (because of assignment prevNumber = givenNumber;) Thus while (7 != 0 && 7 != 0) will pass

Second read from Console - number 0 Thus while (0 != 0 && 7 != 0) will not pass because 0 != 0 is FALSE and while loop ends if condition is result is FALSE

Upvotes: 0

Related Questions