In: Computer Science
The Following Java expression:
S/10 * 10 + 10 – S = C
Show that this expression gives a value of 2 when S contains the int value 78. You must show every step in your working, performing exactly one operation on each line.
I have tried to no end to make sense of this and I know there is an order of precedence in the operators but I can't make any sense of it. Could someone please explain this to me?
Please rate the answer. Feel free to contact me in case of any more clarifications required.
Answer =>
The operator precedence is as follows:
* / % Multiplication, Division, Modulo Left-to-right means whichever comes in the left will get higher precedence.
+ - addition, subtraction Left-to-right
So the expression S/10 * 10 + 10 – S = C will be performed by Java as follows
Step 01. => Replace variables with the original value (S =78). So expression becomes.
78/10 * 10 + 10 – 78
Step 02. => 78/10 will be done first and decimal will be truncated. Division and multiplication have the highest precedence than addition and subtraction.
Here the division (/) will have the highest precedence over multiplication (*) since division is on the left side of the expression.
so the division operator will execute first.
78/10 = 7.8 truncated to 7 and expression will be like
7*10 + 10 -78
Step 03. => 7*10 will be executed as multiplication (*) is precedence over the other operators (+ and -) and expression will become
70 + 10 -78
Step 04. => 70 + 10 will be executed as operator addition (+) is on the left-hand side and will have higher precedence. And the expression will become
80 -78
Step 05. => last the minus (-) operator will be executed and the result will become 2.
Why the java is giving 78/10 as 7 in Step 02., is because the S is an integer. The illustration is given below.
Output