Sunday, July 12, 2009

C for beginners problem....supposed to determine output of relational operators?

My homework asks "What is the output of the following?" and i'm thinking something is horribly wrong with this code or they skipped this in class.





the only thing vaguely tickling my brain is the true/false (1 or 0) thing. but if that's so, i didn't realize you could assign 1 or 0 to integers using true / false tests.





int main()


{


int a = 3, b = -1, c = 0, i, j, k, n;


i = a || b || c;


j = a %26amp;%26amp; b %26amp;%26amp; c;


k = a || b %26amp;%26amp; c;


n = a %26amp;%26amp; !(b || c);


printf("\ni = %d, j = %d, k = $d, n = %d\n", i, j, k, n);


}

C for beginners problem....supposed to determine output of relational operators?
Actually, this code prints out 1, 0, "$d", and 1 (k's value after "n ="), because you have "k = $d" instead of "%d". The output is:





i = 1, j = 0, k = $d, n = 1





Unless that's your typo, maybe you are being taught the value of matching up printf arguments. :-)





If you meant "%d", it's:





i = 1, j = 0, k = 1, n = 0
Reply:C treats anything other than 0 as true even negative values as true.


so if you write anything like i=2%26amp;%26amp;5 it sets value of i to 1.


so i=1 bcoz a and b are true, but j=0 boz of c which is zero means false.


%26amp;%26amp; operator has higher precedence than || so it is true again and hence k=1.


not operator has highest precedence. b||c=true as b is non zero


!(b||c) is false which when anded with a gives false setting n to 0


hence


your result is


i=1


j=0


k=1


n=0
Reply:C has no real concept of true and false. 0 is false and everything else is true. As a matter of fact and (%26amp;%26amp;) is an operator that says if either operand is 0 then return 0 otherwise return 1. Or (||) is an operator that says if either operand is not zero then return 1 else return 0.





This is the concept your teacher is testing you on with this question.
Reply:i = true


j, k, n = false





I think, just by looking at it.





Now, integers can be booleans; %26lt;= 0 is false (example, 0 and -1 are false, anything 0 or below)


And a true integer is anything above 0.


No comments:

Post a Comment