### Thread: Not equal not working!!

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2012
Posts
20
Rep Power
0

#### Not equal not working!!

I can never get the != right in any of my code. Everything compiles without error. I also debug but still cant figure out why i cant skip over this loop. I enter 1 or 2 and it still runs the code inside the while loop. Any help?

[CODE]
int main(){
printf("Please select an option:\n1) Find on what day a specific date falls\n2) Display the twelve month calendar for a given year\n");
int choice = 0;
scanf("%d", &choice);
while((choice != 1) || (choice != 2)){
printf("Entry invalid please enter either 1 or 2\n");
scanf("%d", &choice);
}
printf("Choice is complete: %d", choice);
return 0;
}
2. > while((choice != 1) || (choice != 2))
How do you make this false?

If choice is 1, then it can't be 2, so you get false || true
If choice is 2, then it can't be 1, so you get true || false

Either way, you loop forever.

Try
while ( !( choice == 1 || choice == 2) )
3. It != that is "not working" - that is hardly plausible! Rather it is your boolean logic lat his flawed. See here and here.

Boolean logic and algebra are the fundamental mathematics of computing. You need at least an intuitive of not a rigorous mathematical understanding of it.

Originally Posted by salem
Try
while ( !( choice == 1 || choice == 2) )
Which is equivalent also to:

Code:
`while( choice != 1 && choice != 2 )`
You can take your pick, I suggest the latter since it only requires a single change of operator to correct your code. Intuitively you might describe the first as:

"while neither 1 nor 2",

and the second as:

"while not 1 and not 2"

you can see that in English they mean the same thing, whereas your (arbitraryproc's, not salem's) code reads

"while not 1 or not 2",

which is true for any value, because when its 1 its not 2, and when 2 its not 1, and when it is anything else its neither 1 nor 2!

Consider the following:

NOT(A) AND NOT(B) == NOT(A OR B)
NOT(A) OR BOT(B) == NOT(A AND B)

these are known as De Morgan's Laws
Last edited by clifford; September 1st, 2012 at 04:37 PM.
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2012
Posts
20
Rep Power
0
Damn I'm stupid....... Sorry guys. lol Ive definitely wasted some board space on this question