Modulus on negative numbers in C language

C language modulus operator with negative values: Here, we are going to learn about the behaviour of modulus operator with the negative numbers.
Submitted by IncludeHelp, on April 14, 2019

The modulus operator (%) operator in C

The modulus operator is an arithmetic operator in C language; it is a binary operator and works with two operands. It is used to find the remainder.

Syntax:

    operand1 % operand2; 

It returns the remainder which comes after dividing operand1 by operand2.

Example:

    Input:
    int a = -10;
    int b = 3;

    // finding remainder
    result = a%b;
    printf("result = %d\n", result);

    Output:
    result = -1

C code to demonstrate example of modulus operator with positive operands

// C program to demonstrate example of 
// Modules operator (%)

#include <stdio.h>

int main()
{
    int a = 10;
    int b = 3;
    
    int result;
    
    result = a%b;
    
    printf("result = %d\n", result);
    
    return 0;
}

Output

    result = 1

Modulus operator with negative numbers

If we have negative numbers, the result will be based on the left operand's sign, if the left operand is positive – the result will be positive, and if the left operand is negative – the result will be negative.

Thus, in the result (remainder), the sign of left operand is appended.

Understand with the below table:

    Left operand    Right operand 	Result 
    Positive	    Positive 		Positive
    Positive	    Negative		Positive
    Negative 	    Positive		Negative
    Negative	    Negative		Negative

Example:

    Input:
    int a = -10;
    int b = 3;

    // finding remainder
    result = a%b;
    printf("result = %d\n", result);

    Output:
    result = -1

C code to demonstrate example of modulus operator with negative operands

// C program to demonstrate example of 
// Modules operator (%)

#include <stdio.h>

int main()
{
    int a = -10;
    int b = 3;
    
    int result;
    
    result = a%b;
    printf("result = %d\n", result);
    
    a = 10;
    b = -3;
    result = a%b;
    printf("result = %d\n", result);    

    a = -10;
    b = -3;
    result = a%b;
    printf("result = %d\n", result);    
    
    return 0;
}

Output

result = -1
result = 1
result = -1




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.