The Wizard
The Wizard

Reputation: 953

Logical expression in C

I am stuck at the following question from class. Using precedence, solve the following logical expression: 1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 9 / 10 > 0
I used the following steps to do the problem first
-> 1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 9 / 10 > 0
-> 1 && 3 - 4 < 5 && 6 <= 7 >= 8 != 1 > 0
-> 1 && -1 < 5 && 6 <= 7 >= 8 != 1 > 0
-> 1 && 1 && 1 >= 8 != 1 >0
-> 1 && 1 && 0 != 1 >0
-> 1 && 1 && 0 != 1
-> 1 && 1 && 1
-> 1 , so I suppose the answer is one, but when I try it using a C program, the answer is 0. (Code is shown below.)


#include <stdio.h>
int main(int argc, char* argv[]){
    int x = 1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 9 / 10 > 0;
    printf("1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 9 / 10 > 0 = %d\n", x);
    return 0;
}

Upvotes: 0

Views: 525

Answers (2)

Mestica
Mestica

Reputation: 1529

Please take note the precedence of operators in C(it's like pemdas rule in math):

* / % + - << >> < <= > >= == != 

The right most expression

6 <= 7 >= 8 != 9 / 10 > 0 

is evaluated to be 0. And your using && logical expression so expect that for the whole expression the result will be 0.

Upvotes: 0

Red Alert
Red Alert

Reputation: 3816

In c, integer division does not do any rounding. So the 9/10 is 0 with 9 remainder, and the remainder is thrown out for the / operator (for the % operator, it's the other way around). This code results in a 1, like you would expect:

#include <stdio.h>
int main(int argc, char* argv[]){
    int x = 1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 10 / 10 > 0;
    printf("1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 10 / 10 > 0 = %d\n", x);
    return 0;
}

Upvotes: 1

Related Questions