Saturday 1 September 2012

December 2010 Question Paper - Question No 12

12. The value of the following expression (13 / 4 * 3) % 5 + 1 is
(A) 5.75
(B) 2.95
(C) 1.4875
(D) 5
The answer is (D)




Explanation:-

The explanation for this question is very simple. According to the precedence of the different binary operators in C, * / and % precedes that of + and -. Since the expression enclosed in parenthesis is executed first, the expression which would be executed first is (13 / 4 * 3). Since all these operators precedence is the same, they would execute from left to right and so 13 / 4 gets executed first.
13 / 4 = 3
This intermediate answer is multiplied with 3 in order to get the answer 9.
3 * 3 = 9
The next expression would be 9 % 5. The result is 4.
% is the mod operator. It gives the remainder of dividing two numbers.
9 % 5 = 4
Finally this 4 is added to 1 to get the final result of 5.
It is always better to just know the precedence chart table of the different operators in C.

No comments:

Post a Comment