Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the modulo operator as a function in C

How can we implement the modulo operator as a function in C without using the operator?

like image 693
Yktula Avatar asked Apr 18 '10 03:04

Yktula


People also ask

What operator is used to implement the modulo operation in C?

We use the % to denote this type of operator (it's the percentile operator). The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result.

How is modulus operator implemented?

Modulus operator works based on the value received by the end-user. It always finds the remainder of 2 numbers with respect to the numerator. The below example will illustrate the exact functionality. Example: 7 % 3 gives us remainder as 1 because when we divide 7 by 3 then we get 2 as quotient and 1 as remainder.

How do you calculate modulus in C?

rem = num1 % num2; We calculate the remainder using the Modulus(%) operator. printf("Remainder = %d", rem); printf("Remainder = %d", rem);


Video Answer


1 Answers

Do an integer division followed by a multiplication, and subtract.

#include <stdio.h>
int main()
{
  int c=8, m=3, result=c-(c/m*m);
  printf("%d\n", result);
}
like image 116
Ignacio Vazquez-Abrams Avatar answered Nov 09 '22 20:11

Ignacio Vazquez-Abrams