Unit 7 Lesson 2 - MOD Operator

I am having trouble understanding the MOD Operator %. When I look up videos, the descriptions do not match what is BRIEFLY said in Unit 7 Lesson 2 Level 2; example:
// the MOD operator “%” - divides two numbers and returns the remainder
// in this case - if a number divided by two has a remainder of zero, it’s an even number

A. (5%2) according to code.org is 2 with a remainder of 1
B. If we divide 5 by 2, the result is 2.5 (so I am confused by statement in A)

A. (2%3) according to code.org is 2
B. If we divide 2 by 3, the result is .6666666667 (so I am confused by statement in A)

So I am totally confused. Is there a video somewhere that explains the MOD operator? I watched the following video:

When using the mod operator you only do integer division. You stop the division when you start getting decimals. 5/2 divides once and with a quotient of 2 and a remainder of 1. If you divide any further, you will start getting decimals.

Another way to look at this is to keep mulitiplying by 2 till you get as close as you can to 5 without going over. Since 2 x 2 = 4 and 2 x 3 = 6, we stop at 2 get a quotient of 2. What is left over is 5 - 4 = 1. The answer to 5%2 is 1. Let’s look at a bigger number 31 % 2 = 1. Since 2 x 15 is 30 and 2 x 16 = 32, we get a quotient of 15. What is left over is 31 - 30 = 1. That is the remainder.

For 2%3, since we cannot divide 2 by 3, the quotient is 0 and reminder is 2.

Try this video - What is Modulo? Using the Modulo Operator in Python and Swift Tutorial - YouTube

I hope this helps.

Whenever I go through Mod with my students, I resort to showing examples in good old long division:

It is something they instantly recognize and helps them get it.

1 Like

Here is 2 mod 3:

2 mod 4 works the same way.

1 Like