Can someone please explain the % part of this answer? I know that, for example, 20 % 3 would be 2 but do not understand how 2 % 3 is 2.
http://www.danchisholm.net/dec20/topic/section5/operators1.html Question 10
class EBH002 {
static int m(int i) {
System.out.print(i + ", ");
return i;
}
public static void main(
String s[]) {
m(m(1) + m(2) % m(3) * m(4));
}}
What is the result of attempting to compile and run the program?
a. Prints: 1, 2, 3, 4, 0,
b. Prints: 1, 2, 3, 4, 3,
c. Prints: 1, 2, 3, 4, 9,
d. Prints: 1, 2, 3, 4, 12,
e. Prints: 2, 3, 4, 1, 9,
f. Prints: 2, 3, 4, 1, 3,
g. Run-time error
h. Compile-time error
i. None of the above
The expression can be simplified as follows: 1 + 2 % 3 * 4 = 9. The original expression is as follows: m(m(1) + m(2) % m(3) * m(4)). Simplification step one. Evaluate each operand from left to right: m(1 + 2 % 3 * 4). Step two. Add parentheses to indicate operator precedence and associativity: m(1 + ((2 % 3) * 4). Step three. Evaluate the inner-most parentheses: m(1 + (2 * 4)). Step four. Evaluate the inner-most parentheses: m(1 + 8). The result is 9.