Integer Division ( % )

What is it?

Integer Division differs from standard division in that the quotient returned is rounded down to the nearest whole number, eliminating any ‘leftover’ fractions. So, while 15 divided by 2 using standard division would give you a quotient of 7.5, doing the same with integer division produces a quotient of 7.

Only numeric data types can be used with this operator. All other types must be converted to an integral type first. Despite the name, the operator will accept non-integer numbers as well as integers.

What is the Syntax?

The integer division operator’s syntax is as follows:

Numerator % Denominator

Why might I want to use this?

Any time the items you are dividing cannot be reduced to fractions. For example, dividing 11 coins between 4 children cannot be done evenly, so you could use integer division to determine the maximum each child can receive as an equal share.

Let’s say the baker from our standard division example above is still measuring out the ingredients for his scones. It takes a single egg to produce 8 scones, and we already established he can produce no more than 20 scones due to the amount of flour he has currently. Since it is impractical to divide the contents of an egg and the baker doesn’t want to use more eggs than necessary, we need to know how many batches of 8 scones can be accommodated by our flour limit. This will tell us how many eggs to use.

NumberOfEggs := MaxScones % SconesPerEgg

If we were using standard division, the operation 20 / 8 would give us 2.5 eggs. Instead, we use integer division to evaluate 20 % 8, which equates to 2 eggs. Then, using multiplication, we calculate that these 2 eggs will produce a batch of 16 scones.

 

<< Previous: Division ( / ) | Next: Exponent ( ^ ) >>