Skip to main content

Section 3.10 Remainder Operator

Say you know that someone is 68 inches tall, and you want to express their height in feet and inches. As we just saw, dividing 68 by 12 will give you a whole number answer - in this case, 5. How do you calculate the leftover inches?
When you first learned division, you likely learned to write the answer to 68 / 12 as β€œ5r8” meaning β€œ12 divides into 68 5 times with a remainder of 8”. When working with integers the / operator in C++ works in a similar way. It only produces the whole number quotient (the β€œ5”). To get the remainder C++ provides the modulo operator (%), which divides two numbers and computes the remainder.
Using division and modulo, we can convert to feet and inches like this:
Listing 3.10.1.
The first line yields 5. The second line, which is pronounced β€œheight mod 12”, yields 8. So 68 inches is 5 feet, 8 inches.
Modular arithmetic turns out to be surprisingly useful. For example, you can check whether one number is divisible by another: if x % y is 0, then x is divisible by y. You can use the remainder operator to β€œextract” digits from a number: x % 10 yields the rightmost digit of x, and x % 100 yields the last two digits. Many encryption algorithms use remainders extensively.

Checkpoint 3.10.1.

Checkpoint 3.10.2.

How do you know whether the variable x is odd?
  • Use x % 2, and if the result is 0, it is odd.
  • If you divide a number by two and it has no remainder, that means it is an even number!
  • Use x % 2, and if the result is 1, it is odd.
  • If you divide a number by two and it has a remainder of one, that means it is an odd number!
  • Use x / 2, and if the result is 0, it is odd.
  • Dividing a number by two won’t give us the information we want.
  • Use x / 2, and if the result is 1, it is odd.
  • Dividing a number by two won’t give us the information we want.
Hint.
Odd numbers have a remainder of 1 when divided by 2.
You have attempted of activities on this page.