In: Computer Science
Explain the results of the following expressions (you may want to show each step of evaluation):
• 4 + 5 * 6 + 7 / 8
• 4 + 5 * 6 < 7 / 8
• 4 + 5 > 6 && 7 < 8
• 1 && 0
(1) 4 + 5 * 6 + 7 / 8
Answer-
Step (i) To solve this question first we have to find the precedence of all operator
So according to precedence of operator multiplication (*) and divide( /) have a higher precedence then plus ( + ) and ( - ) . so first we have to calculate multiplication and divide.
After solving the multiplication and divide-
We know 5 * 6 is 30 and 7 / 8 is 0.
So 4 + 30 + 0
Step (ii) - now we have to calculate + operation so if one or more operator having same precedence then it will solve with the help of associativity. So in our condition associativity of + operator is Left to right so it will solve left to right.
4 + 30 + 0 (solve Left to Right)
So 34 is answer.
(2) 4 + 5 * 6 < 7 / 8
In this example we have two type of operator Arithmatic and relational operator.
So according to rule Arithmatic operators have greater precedence then Relational operator.
So first we calculate +, * and /.
So we know * and / having greater precedence so they solve first.
We know 5 * 6 is 30 and 7 / 8 is 0.
4 + 30 < 0
Now calculate + operator
34 < 0 (this condition is false so it return 0)
Now we calculate relational operator and its return 0 and 1 value.
So in our case condition is false.
So 0 is answer.
(3) 4 + 5 > 6 && 7 < 8
Step ( i) We know Arithmatic operator have greater precedence then Relational and logical And operators.
So first solve + operator-
9 > 6 && 7<8
Step ( ii ) now we know relational operator having more precedence then logical Operator so-
We know 9 is greater then 9 and 7 is less then 9 so both return 1.
1 && 1
In && operator if both digit is non zero then it return True. in our case bot digit is non zero .
So 1 (True) is Answer
(4) 1 && 0
We know that logical && operator return true (1) if both digit is non zero . in our case first digit is one that is non zero but second digit is 0.
So it return false(0).
So 0 is answer