How is it 2? (Modulus Question)

So I ran the following code in my compiler:
1
2
int k = 24 / 9 % 5;
cout << k << endl;

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.
Last edited on
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 gives you the remainder of an integer operation where divide gives you the number of times a number can fully go into another.

In modulus, if the first number is < the second number return the first number.
3 % 5 = 3
4 % 5 = 4
1 % 5 = 1


In modulus, if the first number is > the second number, subtract the second number from the first until the first number is less than the second.
16 % 5 = ?
16 - 5 = 11
11 % 5 = ?
11 - 5 = 6
6 % 5 = ?
6 - 5 = 1
1 % 5  = 1

Therefore 16 % 5, 11 % 5, 6 % 5 all give the answer of 1.


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.)


I hope that clears modulus up a bit.
Topic archived. No new replies allowed.