4

I want to check if the / operator has no remainder or not:

int x = 0;    
if (x = 16 / 4), if there is no remainder: 
   then  x = x - 1;
if (x = 16 / 5), if remainder is not zero:
   then  x = x + 1;

How to check if there are remainder in C? and
How to implement it?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
user2131316
  • 3,111
  • 12
  • 39
  • 53

6 Answers6

7

Frist, you need % remainder operator:

if (x = 16 % 4){
     printf("remainder in X");
}

Note: it will not work with float/double, in that case you need to use fmod (double numer, double denom);.

Second, to implement it as you wish:

  1. if (x = 16 / 4), if there is no remainder, x = x - 1;
  2. If (x = 16 / 5), then x = x + 1;

Useing , comma operator, you can do it in single step as follows (read comments):

int main(){
  int x = 0,   // Quotient.
      n = 16,  // Numerator
      d = 4;   // Denominator
               // Remainder is not saved
  if(x = n / d, n % d) // == x = n / d; if(n % d)
    printf("Remainder not zero, x + 1 = %d", (x + 1));
  else
    printf("Remainder is zero,  x - 1 = %d", (x - 1));
  return 1;
} 

Check working codes @codepade: first, second, third.
Notice in if-condition I am using Comma Operator: ,, to understand , operator read: comma operator with an example.

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
3

use the % operator to find the remainder of a division

if (number % divisor == 0)
{
//code for perfect divisor
}
else
{
//the number doesn't divide perfectly by divisor
}
Abinash Sinha
  • 840
  • 6
  • 18
3

If you want to find the remainder of an integer division then you can use the modulus(%):

if( 16 % 4 == 0 )
{
   x = x - 1 ;
}
else
{
   x = x +1 ;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

use modulous operator for this purpose.

if(x%y == 0) then there is no remainder.

In division operation, if the result is floating point, then only integer part will be returned and decimal part will be discarded.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
0

you can use Modulous operator which deals with remainder.

Dayal rai
  • 6,548
  • 22
  • 29
0

The modulus operator (represented by the % symbol in C) computes the remainder. So:

x = 16 % 4;

x will be 0.

X = 16 % 5;

x will be 1

tuckermi
  • 839
  • 6
  • 17