how to evaluate logical expression in programming in c
Answers
Answer:
Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under consideration. They are described below:
Logical AND operator: The ‘&&’ operator returns true when both the conditions under consideration are satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero).
Logical OR operator: The ‘||’ operator returns true even if one (or both) of the conditions under consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b or both are true (i.e. non-zero). Of course, it returns true when both a and b are true.
Logical NOT operator: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.
Explanation:
#include <stdio.h>
int main()
{
int a = 10, b = 4, c = 10, d = 20;
// logical operators
// logical AND example
if (a > b && c == d)
printf("a is greater than b AND c is equal to d\n");
else
printf("AND condition not satisfied\n");
// logical AND example
if (a > b || c == d)
printf("a is greater than b OR c is equal to d\n");
else
printf("Neither a is greater than b nor c is equal "
" to d\n");
// logical NOT example
if (!a)
printf("a is zero\n");
else
printf("a is not zero");
return 0;
}
- The precedence of logical operator is lower than the arithmetic operators so constituent arithmetic sub- expression ( if any ) is evaluated first and then logical operator are applied.
- The precedence of logical operator among themselves is not and or So, the expression a or b and c will be evaluated.
- Important while Evaluating python minimise internal work by following three rules :
- In or evaluation, python only evaluates the second argument if the second argument if the first one is true evaluated.