A modulo operator in c returns the remainder of a division, not a quotient. This program finds remainder without using the modulo (mod) operator.
We wrote the program using Turbo C++ 3.0 compiler installed on a Windows XP 32-bit system. You may use another standard C compiler of your choice. If you do, then make necessary changes to the program source code according to you compiler specifications.
You should be familiar with following c programming concepts before learning this program.
This program is a frequently asked question for aptitude tests and job interviews. So, you must try the write the program yourself and then compare your results with the solution given on this page.
Problem Definition
The program receives an input number – a divisor and a dividend. The quotient of the division is easily obtained using the division operator (/).
Now, you cannot use the modulo operator and have to find another way to find the remainder. You can do it in two steps listed below.
- Find an intermediate number by multiplying quotient * divisor.
- subtract the intermediate number from the dividend.
For example, divisor , dividend , find the remainder.
\begin{aligned}& quotient = 53 / 10 = 3 \\ \\ &intermediate \hspace{2mm} number = 5 * 10 = 50\\ \\ &remainder = dividend - intermediate \hspace{2mm} number\\ \\ &remainder = 53 - 50 = 3 \end{aligned}
See the flowchart for this program given below to understand this logic.
Flowchart – Remainder without Modulo Operation
Program Code – Remainder without Modulo Operation
#include <stdio.h>
#include <conio.h>
void main()
{
int n1,n2,quotient,reminder;
clrscr();
printf("Enter two numbers:\n");
scanf("%d %d",&n1,&n2);
quotient = n1/n2;
reminder = n1 - quotient * n2;
printf("Remainder = %d\n",reminder);
getch();
}
Output
The larger number 255 is the dividend, and the smaller number 33 is the divisor. The division does not return quotient, but the remainder 24.
Enter two numbers:255 33
Reminder = 24