What is the output of the following code? System.out.println (5/2%5) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the output of the following code? System.out.println (5/2%5)

the answer is two, but I'm not sure why. I keep getting this wrong in challenges. leave a like?

23rd Jun 2017, 12:05 PM
Sid Meade
Sid Meade - avatar
6 Answers
+ 11
I don't think that there's a precedence of either division over modulo or the other way around. There are specific ways to interpret the expressions when both operators are on equal precedence. That said, the basic explanation to the output would be: 5/2%5 2%5 2 // m mod n wherein m < n will return m. // this is true for both C++ and Java.
23rd Jun 2017, 12:47 PM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Ok, I searched the internet, if there's the same precedence you solve from the left to the right.
23rd Jun 2017, 12:52 PM
Jonas Schröter
Jonas Schröter - avatar
23rd Jun 2017, 12:46 PM
Jonas Schröter
Jonas Schröter - avatar
0
No. Division takes higher precedence over modulo, so 5/2 = 2, 2 % 5 = 2 ( --> 2/5 = 0)
23rd Jun 2017, 12:42 PM
Jonas Schröter
Jonas Schröter - avatar
0
The confusing thing of that code is that the results of both ways are equal.
23rd Jun 2017, 12:49 PM
Jonas Schröter
Jonas Schröter - avatar
- 1
Modulo takes precedence over division, so first 2%5 is evaluated, which returns 2. This is because 5 doesn't go into 2 at all, so you have a remainder of 2. Then, 5/2 returns the int 2, not the float 2.5, because both the numerator and denominator are integers.
23rd Jun 2017, 12:09 PM
Frederik Bussler
Frederik Bussler - avatar