The output is 2. But I don't understand how it can be 2. No matter what order I manually divide this sequence of numbers, the remainder is never 2. 24 / 9 leaves a remainder of 6. 6 / 5 leaves a remainder of 1. Alternatively, 24 / 5 leaves a remainder of 4. 9 / 5 leaves a remainder of 4.
So how does this line turn up remainder of 2? Y'see, I'm doing review for a test and I need to understand how this works. Clearly I don't understand modulus yet.
When looking at the order of operations, modulus is done after the division has been completed. So first of all 24 / 9 is 2 (at least when working with int). Then 2 % 5 = 2.
This is because 2 / 5 = 0 (when working with integers) with 2 as a remainder.
Modulus will NEVER return a number greater than or equal to the second number.
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
. . .
4 % 5 = 4
5 % 5 = 0 (No remainder after 5/5)
6 % 5 = 1
So for integer N, M%N will return 0 to N-1, for all integers M.
Modulus in C++ is considered to have the same precedence in the order of operations as Division and Multiplication.
Modulus only works with integers.
Integer division never returns a floating-point number. It will truncate the decimal and leave the integer in front.
16 / 5 = 3 (Integer Division)
12 / 5 = 2
3 / 5 = 0 (3 is too small to go into 5 any even number of times.)
24 / 9 = 2 (2*9 = 18. 24 - 18 = 6. 6 < 9, so 2 is returned.)