0

Calculation rules

System.out.println(12 % 9 * 12 % 9 * 12 % 9); Do i calculated first the modulos or the *?

18th Jan 2021, 11:21 AM
Manfred h
2 Answers
+ 5
The precedence of these operators *, / and % is the same and so they are evaluated from right to left in an expression 12 % 9 * 12 % 9 * 12 % 9 So, here 12%9 = 3 would be evaluated first giving us 3 * 12 % 9 * 12 % 9 Then, 3*12 = 36 is evaluated giving us 36%9 * 12 % 9 Then, 36%9 = 0 will be evaluated giving us 0 * 12 % 9 Then, 0*12 = 0 is evaluated giving us 0 % 9 Finally we have 0 % 9 which is 0. Read About order of PRECEDENCE in programming language.
18th Jan 2021, 11:38 AM
minirkk
minirkk - avatar
+ 2
Both % and * have the same precedence. In that case you must look for associativity, which is left to right in this case. So solve from left to right.
18th Jan 2021, 11:39 AM
Avinesh
Avinesh - avatar