C program to find the remainder without using modulo operator

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 :

  1. First of all, read the number and divisor as entered by the user.
  2. Keep subtracting the divisor from the number and set the value to the number until the number becomes smaller than the divisor.
  3. If the number becomes smaller than the divisor, it should be the required remainder.
  4. 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:

  1. Create three integer variables to store the value of the number (no), divisor (divisor), and the remainder (remainder).
  2. Ask the user to enter the number and store it in the variable no.
  3. Ask the user to enter the divisor and store it in the variable divisor.
  4. 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.
  5. Assign the final value of no to the variable remainder.
  6. 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: