Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 73

4


Integer Division and Modulus
Integer division is the division you learned when you were in elementary school. When
you divide 21 by 4 (21 / 4), and you are doing integer division, the answer is 5 (with a
remainder).
The fifth mathematical operator might be new to you. The modulus operator (%) tells you
the remainder after an integer division. To get the remainder of 21 divided by 4, you take
21 modulus 4 (21 % 4). In this case, the result is 1.
Finding the modulus can be very useful. For example, you might want to print a state-
ment on every 10th action. Any number whose value is 0 when you modulus 10 with that
number is an exact multiple of 10. Thus 1 % 10 is 1, 2 % 10 is 2, and so forth, until 10
% 10, whose result is 0. 11 % 10 is back to 1, and this pattern continues until the next
multiple of 10, which is 20. 20%10 = 0 again. You’ll use this technique when looping is
discussed on Day 7, “More on Program Flow.”

FAQ
When I divide 5/3, I get 1. What is going wrong?
Answer:If you divide one integer by another, you get an integer as a result.
Thus, 5/3 is 1. (The actual answer is 1 with a remainder of 2. To get the remainder, try
5%3, whose value is 2.)
To get a fractional return value, you must use floating-point numbers (type float,
double, or long double).
5.0 / 3.0 gives you a fractional answer: 1.66667.
If either the divisor or the dividend is a floating point, the compiler generates a floating-
point quotient. However, if this is assigned to an l-value that is an integer, the value is
once again truncated.

Combining the Assignment and Mathematical Operators ....................................


It is not uncommon to want to add a value to a variable and then to assign the result back
into the same variable. If you have a variable myAgeand you want to increase the value
stored in it by two, you can write
int myAge = 5;
int temp;
temp = myAge + 2; // add 5 + 2 and put it in temp
myAge = temp; // put it back in myAge
Free download pdf