Section 5b

Integer Math - Multiplication and Division


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Multiplication & Quotient-Division

The basics. Multiplication and division that results in a quotient are almost exactly as you would expect. Consider the following.

int numCandyBarsInBox = 25;
int numberOfboxes = 12;
int numberOfCandyBars = numCandyBarsInBox * numberOfBoxes;

With 25 candy bars in a box and 12 boxes, we can calculate the number of candy bars we have. There are no surprises with integer multiplication.

However, if we want to break a box up between two people, we can do the following.

int halfCandyBarBox = numCandyBarsInBox / 2;

According to this math, there are 12 candy bars in half a box. Integer math has no fractional quantity. With integer math, there is a quotient and a remainder. The quotient is a whole (i.e., integer) number as is the remainder, which will be discussed soon.

The important thing to note is that since integers cannot hold fractional quantities at all, values do not round; the result is said to be truncated, meaning anything to the right of what would have been a decimal point is removed. Consider the following:

int quotient_1 = 2 / 3; // answer is zero
int quotient_2 = 99 / 100; // answer is still zero

In the case of the candy bar, it would not be appropriate to cut the middle candy bar in half because then it is ruined for sale. With integers, you deal with whole quantities. Another example:

int numTouristsOnBus = 79;
int halfBusLoad = numTouristsOnbus / 2;

The halfBusLoad variable now holds 39; again, it is inappropriate to have half a person. That is both the value and the necessity of conducting integer math; it represents reality.

Watch this video and work the code alongside. There are some important things to observe and learn with these integer math operations.