Syntax: If x and y are integers, then the expression:
x % y
produces the remainder when x is divided by y.
- If y completely divides x, the result of the expression is 0.
- If x is not completely divisible by y, then the result will be the remainder in the range [1, x-1].
- If x is 0, then division by zero is a compile-time error.
For example: Consider the following code:
3 1 0
Restrictions of the modulo operator:
The modulo operator has quite some restrictions or limitations.
- The % operator cannot be applied to floating-point numbers i.e float or double. If you try to use the modulo operator with floating-point constants or variables, the compiler will produce a error:
Compilation Error in C code :- prog.c: In function 'main': prog.c:19:16: error: invalid operands to binary % (have 'float' and 'float') result = x % y; ^
The sign of the result for modulo operator is machine-dependent for negative operands, as the action takes as a result of underflow or overflow.
-3 0 -3
Note: Some compilers may show the result of the expression as 1 and other may show -1. It depends on the compiler.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Program to find remainder without using modulo or % operator
- vector::operator= and vector::operator[ ] in C++ STL
- deque::operator= and deque::operator in C++ STL
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Operator Overloading '<<' and '>>' operator in a linked list class
- 3-way comparison operator (Space Ship Operator) in C++ 20
- Compute n! under modulo p
- Chinese Remainder Theorem | Set 2 (Inverse Modulo based Implementation)
- Euler's criterion (Check if square root under modulo p exists)
- Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
- Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
- Find sum of modulo K of first N natural number
- Primitive root of a prime number n modulo n
- Maximum subarray sum modulo m
- Modulo 10^9+7 (1000000007)
- Multiply large integers under large modulo
- Fibonacci modulo p
- Discrete logarithm (Find an integer k such that a^k is congruent modulo b)
- Exponential Squaring (Fast Modulo Multiplication)
- Divisibility by 3 where each digit is the sum of all prefix digits modulo 10
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : shubhamkumarlhh