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:
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.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.
You have attempted of activities on this page.