The Modulo Operator

The % operator computes the remainder after floor division. 14 % 4 is 2 218 % 5 is 3

Remainder with %
The % operator computes the remainder after floor division.
• 14 % 4 is 2
• 218 % 5 is 3
Applications of the % operator
• Obtain the last digit of a number: 230857 % 10 is 7
• Obtain the last 4 digits: 658236489 % 10000 is 6489
• See whether a number is odd: 7 % 2 is 1, and 42 % 2 is 0
Why floor and modulo division are useful
Floor division allows us to extract the integer part of the division while the modulo operator extracts the remainder part of the division. Consider the question:
How many weeks and days are there in 25 days? Answer: 3 weeks plus 4 days.
Why the modulo operator is useful
If today is a Tuesday, which day is 43 days from today? Answer: 43 divided by 7 is 6 with a remainder of 1. Thus, it will be Wednesday.
Even and odd: a number x is even if x % 2 is 0, and odd if x % 2 is 1.
Making change
Find the exact change for 137 cents using quarters, dimes, nickels and cents, using the least number of coins. Floor division answers how many, and modulo answers what is left over.
• How many quarters? 137 // 25 = 5 quarters
• What's leftover? 137 % 25 = 12 cents
• How many dimes? 12 // 10 = 1 dime
• What's leftover? 12 % 10 = 2 cents
• How many nickels? 2 // 5 = 0 nickels
• What's leftover? 2 % 5 = 2 cents
• How many pennies? 2 // 1 = 2 pennies
• What's leftover? 2 % 1 = 0 cents. Done!
Extracting digits
Given a three-digit integer, extract its ones, tens and hundreds digits. For example, if the integer is 352, its ones digit is the 2, its tens digit is the 5 and its hundreds digit is the 3.
Alternatively, without changing the variable as you go: