C program to find remainder without using modulo operator :
In this tutorial, we will learn how to find the remainder without using the modulo operator (%) in C programming language. The algorithm that we are going to use is as below :
Algorithm :
- First of all, read the number and divisor as entered by the user.
- Keep subtracting the divisor from the number and set the value to the number until the number becomes smaller than the divisor.
- If the number becomes smaller than the divisor, it should be the required remainder.
- Print out the result.
For example, if the number is 10 and the divisor is 3. First, we will calculate 10 - 3, which is 7 and this value is assigned to the number. Repeating the same step, it will be 7 - 3, i.e. 4. In the next step, it will be 4 - 3 = 1. Since 1 is smaller than 3, it is the remainder.
Let’s take a look into the program :
C program :
#include <stdio.h>
int main()
{
// 1
int no, divisor, remainder;
// 2
printf("Enter the number : ");
scanf("%d", &no);
// 3
printf("Enter the divisor : ");
scanf("%d", &divisor);
// 4
while (no >= divisor)
{
no = no - divisor;
}
// 5
remainder = no;
// 6
printf("The remainder is %d ", remainder);
return 0;
}
Explanation :
The commented numbers in the above program denotes the step numbers below:
- Create three integer variables to store the value of the number (no), divisor (divisor), and the remainder (remainder).
- Ask the user to enter the number and store it in the variable no.
- Ask the user to enter the divisor and store it in the variable divisor.
- Run one while loop. Check if no is greater than divisor and if yes, store the value of no - divisor in no. Do this till the value of no become smaller than the divisor.
- Assign the final value of no to the variable remainder.
- Finally, print out the value of remainder.
Sample Output :
Enter the number : 12
Enter the divisor : 4
The remainder is 0
Enter the number : 555
Enter the divisor : 4
The remainder is 3
You might also like:
- C programming structure explanation with example
- C program to find total number of sub-array with product less than a value
- C program to find total lowercase,uppercase,digits etc in a string
- C program to read user input and store them in two dimensional array
- C programming tutorial to learn atof, atoi and atol functions