Until the loop checks all conditions correctly?
So the assignment is like this: you can enter all kinds of numbers, but when you enter 0 twice in a row, it needs to be stopped. The first time you enter a number, you are not allowed to enter 0.
This is the code I have installed:
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 only entered one 0. For example, if I entered 7 first to start and my next number would be 0. When I debug it, it says my preset number is 0 and prevNumber is 7 when it returns to the while condition, which stops and ends. When the program finishes debugging, it explicitly says prevNumber = 7 and givenNumber = 0. I'm using conditional AND right, right?
Any hint? I am not allowed to use arrays for this question.
Thank you in advance
source to share
Oh, right, you have the wrong logic. It should be like this:
while ((givenNumber != 0) || (prevNumber != 0)) {
Check out DeMorgan laws to find out why ...
source to share
Your problem is with your conditional statement.
You are currently checking if both the given number and PrevNumber 0 are not equal.
So, if none of them is 0, then the operator will evaluate to TRUE. However, if any of the numbers is 0, then the operator will evaluate to FALSE, since (TRUE) && (FALSE) evaluates to FALSE.
There are two ways to fix this: you can use || (the "OR" operator) with two "! =" operators, or you can negate the whole thing and use regular equality rather than "! =" as such :! (givenNumber == 0 && prevNumber == 0)
source to share
while (givenNumber! = 0 & prevNumber! = 0)
For the first value read from the console - the number 7 givenNumer will be 7 prevNumber will also be 7 (due to the assignment prevNumber = givenNumber;) So although (7! = 0 & 7! = 0) will pass
The second read from the console is number 0 So although (0! = 0 & 7! = 0) won't get through because 0! = 0 is FALSE and while ends if the condition is FALSE
source to share