Subject: C' Programming For Problem Solving Subject Code: 18CPS23
Subject: C' Programming For Problem Solving Subject Code: 18CPS23
0 1 0 1
(Non-Zero)
1 0 0 1
(Non-Zero)
1 1 1 1
(Non-Zero) (Non-Zero)
Logical Operators (CONTD….)
OP1 !(OP1)
1
0 (Non-Zero)
1
0
(Non-Zero)
Logical Operators (CONTD….)
Some Examples of the Usage of Logical Expressions are:
Example1: if age = 20 and salary = 10000, then
if(age > 55 && salary < 15000)
or
if((age > 55) && (salary < 15000))
if((20 > 55) && (10000 < 15000))
if( 0 && (10000 < 15000))
if( 0 && 1 )
if(0)
Here, the if condition becomes FALSE.
Logical Operators (CONTD….)
Example2: if number = 20, then
if(number < 0 || number > 100)
or
if((number < 0) || (number > 100))
if(( 20 < 0) || ( 20 > 100))
if( 0 || ( 20 > 100))
if( 0 || 0 )
if(0)
Here, the if condition becomes FALSE.
Logical Operators (CONTD….)
Rules for Logical Operator Evaluation:
First evaluate () from Left to Right if any.
Evaluate Unary Operator from Right to Left if any.
Evaluate *, / and % from Left to Right if any.
Evaluate + and – from Left to Right if any.
Evaluate <, <=, > and >= from Left to Right if any.
Evaluate == and != from Left to Right if any.
Evaluate && operator from Left to Right if any.
Evaluate || operator from Left to Right if any.
Finally use Assignment Operator.
Example1: If a=11, b=6, c=0, d=7 and e=5 then evaluate
a + 2 > b || !c && a == d || a - 2 < = e
a + 2 > b || !c && a == d || a - 2 < = e
11 + 2 > 6 || !0 && 11 == 7 || 11 – 2 <= 5
11 + 2 > 6 || 1 && 11 == 7 || 11 – 2 <= 5
13 > 6 || 1 && 11 == 7 || 11 – 2 <= 5
13 > 6 || 1 && 11 == 7 || 9 <= 5
1 || 1 && 11 == 7 || 9 <= 5
1 || 1 && 11 == 7 || 0
1 || 1 && 0 || 0
1 || 0 || 0
1 || 0
1
Example2: If a=11, b=6, c=4, d=7 and e=5 then evaluate
a + 2 > b || !c && a == d || a - 2 < = e
a + 2 > b || !c && a == d || a - 2 < = e
11 + 2 > 6 || !4 && 11 == 7 || 11 – 2 <= 5
11 + 2 > 6 || 0 && 11 == 7 || 11 – 2 <= 5
13 > 6 || 0 && 11 == 7 || 11 – 2 <= 5
13 > 6 || 0 && 11 == 7 || 9 <= 5
1 || 0 && 11 == 7 || 9 <= 5
1 || 0 && 11 == 7 || 0
1 || 0 && 0 || 0
1 || 0 || 0
1 || 0
1
Example3: Evaluate the following expression
22 + 3 <= 6 && !5 || 2 == 7 && 22 – 2 >= 5
22 + 3 <= 6 && !5 || 2 == 7 && 22 – 2 >= 5
22 + 3 <= 6 && 0 || 2 == 7 && 22 – 2 >= 5
25 <= 6 && 0 || 2 == 7 && 22 – 2 >= 5
25 <= 6 && 0 || 2 == 7 && 20 >= 5
0 && 0 || 2 == 7 && 20 >= 5
0 && 0 || 2 == 7 && 1
0 && 0 || 0 && 1
0 || 0 && 1
0 || 0
0
Write the Output of the following code.
void main()
{
int a=5, b=2, res1;
float f1=5.0, f2=2.0, res2;
res1=5/2.0+a/2+a/b;
res2=f1/2*f1-f2;
printf(“res1 = %d and res2 = %f”,res1,res2);
}
OUTPUT:
expression.
exp3) is evaluated.
Conditional Operators (CONTD….)
True
x = (a > b) ? a : b;
exp1 exp2 exp3
then x = a
then x = b
Conditional Operators (CONTD….)
Example1: consider the following statements:
if a = 10;
b = 15;
x = (a > b) ? a : b;
In this example, x will be assigned the value of b.