Emulating the Modulus Operator

Difficulty: ★ ★ ☆ ☆

I think any kid learning math in school knows what a remainder is, but few understand (or are taught) what a modulus is. It obtains the remainder of one value divided by another, specifically a larger value divided by a smaller value. In C programming, the % (modulo) operator performs this calculation. But what if the C language lacked a modulo operator?

Your task for this month’s Exercise is to emulate the modulus operator. Or is it the modulo operator? Whatever. Write a function, mod(), that accepts two integers as an argument and returns the remainder for the first divided by the second — the modulus.

Here is sample output from my solution:

Enter two integers separated by a space: 33 7
% operator: 33 % 7 = 5
mod() function: 33 % 7 = 5

As shown above, your program should prompt for two integer values. The next two lines show output manipulating the values. The first uses the % operator, the second the mod() function. Both results are the same, which proves the function’s success.

Please try this exercise on your own. Click here to view my solution.

Leave a Reply