Tabs

Sunday, 16 September 2012

Chapter 8 - The Modulus Operator

In the previous chapters i purposely skipped one important math operator. Its called the Modulus or mod operator ( % ). Explaining this in the previous chapters would add to the confusion and hence i am writing a mini post for this special operator. In the time to come you will be using this quite often in solving certain problems.

What does this Operator do ?

This operator returns the remainder of division. To illustrate its working look at the image below

Here 7 % 2 will give an output of 1.

Similarly

4 % 5 = 4

12 % 3 = 0

54 % 4 = 2

Significance of this operator

Look and the results in each case and notice that the results ( i.e. the remainder is always less than divisor )

Also that if the divisor ( 3 in example 2) divides the dividend ( 12 ) then the output will be 0

Where can you use this operator

You can use this operator to determine whether a number (divisor) completely divides other number (dividend).

Extending this logic we can determine if a number is odd or even by using 2 as divisor.

You can also use this operator to reduce a number to some number less than the divisor

Example: Consider large numbers like 12344. Using 12344 % 5 you can reduce this number to 4. Similarly you can reduce 845 can be reduced to 0.

This may not seem useful now but you may need to use this to solve certain problems.

Activities:

I have purposely skipped the code. So your first task is to write a simple code printing the result.

Adjust the values of operand 1 and operand 2 two and examine the result.