views:

89

answers:

3

Hi there,

Can someone please explain what really goes on in this code ? If I put the AND statement, the message wont show if values are less than 0 or greater than 10 ... I think I must use 1 0 logic to work this out right ? I just need someone to briefly explain it please.

#include<stdio.h>
main(){

  puts("enter number");
  scanf("%d",num);
  if(num<0 || num >10)
     puts("yay");
}

How is that IF statement different when AND is put :

#include<stdio.h>
main(){

  puts("enter number");
  scanf("%d",num);
  if(num<0 && num >10)
     puts("yay");
}

Thanks !!

+2  A: 

This is based on Boolean logic:

true || true -> true
true || false -> true
false || true -> true
false || false -> false

true && true -> true
true && false -> false
false && true -> false
false && false -> false

Notice how those differ when one side is true and the other is false.

Anyway, in your test:

if(num<0 && num >10)

It's not possible for a number to both be < 0 and at the same time be > 10. Because of this, you will either evaluate true && false (for negative numbers), false && false (for numbers between 0 and 10 inclusive) or false && true (for numbers larger then 10). In all those cases, the boolean logic says the answer is false.

R Samuel Klatchko
Exactly what I was looking for, thanks !!
ZaZu
+2  A: 

Boolean logic.

If you use || (OR), the statement is true if ANY of the conditions are met. If you use && (AND), the statement is true ONLY if ALL of the conditions are met. SO in your second example, the statement will be true if the number is BOTH smaller than 0 AND larger than 10. Clearly there is no such number.

Roadmaster
Thanks for replying :)
ZaZu
+2  A: 

1) I believe you forgot some char in scanf string:

scanf("%d",&num);

2) first example will say "yay" if number is LESS THAN 0 or GREATER THAN 10

second example will never say "yay" b/c number must be LESS THAN 0 and GREATER THAN 10 simultaneously

zed_0xff
THanks for the info, yeah I just type down a random program here ... thanks!
ZaZu