1

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 !!

3
  • 1
    (a) You need to declare num and (b) you need to pass a pointer to num to scanf(), not num itself. You probably could also use an introductory computer science text. Commented Jun 2, 2010 at 23:06
  • 2
    Can you think of a number that is both less than zero and greater than ten? Commented Jun 2, 2010 at 23:08
  • @James, Yes I know that, thanks for pointing them out, I just wrote down a random program here .. so missed out those .... @walky, Nope, but I was looking for an explanation as mentioned below, thanks for the reply though Commented Jun 2, 2010 at 23:22

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.