Am I performing my order of operations incorrectly in Java?

Viewed 82

I'm having a bit of trouble with this question.

I'm unsure where % (mod) sits on the BEDMAS order of operations.

37 % 20 % 3 * 4 = ?

My mental arithmetic answer is 5 but I must be doing something wrong. Where does % mod sit within BEDMAS?

3 Answers

The modulu (%) operator has the same precedence as the division (/) operator, so:

37 % 20 is 17
17 % 3 is 2
2 * 4 is 8

IDEOne output

BEDMAS is misleading as it suggests Division before Multiplication. It is more something for primary school.

It should be

  1. multiplicative operations: * / %
  2. additive (binary) operations: + -

Brackets, unary (-), bits and logic operations not entirely covered by BEDMAS too.

    (((37 % 20) % 3) * 4) = 8

And not Multiplication after Modulo:

    ((37 % 20) % (3 * 4)) = 5  ***

I just tested this and java outputs the exactly right result. 37 % 20 = 17, 17 % 3 = 2, 2 * 4 = 8. But refer to MathExchange for your BEDMAS question

Related