Open In App

Modulo Operator (%) in C/C++ with Examples

Last Updated : 30 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C or C++, the modulo operator (also known as the modulus operator), denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division which is also called the modulus of the operation.

Syntax of Modulus Operator

If x and y are integers, then the expression:

x % y;

pronounced as “x mod y”. For example, 10 % 2 will be pronounced as ” Ten mod Two”.

Return Value of Modulo Operator

  • 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 [0, y-1]
  • (x % y) < (x / 2) ………if (x >= y)
  • (x % y) = x ……… if (x < y)
  • If y is 0, then division by zero is a compile-time error.

Example of Modulo Operator

Below is the C/C++ program to demonstrate the working of the modulo operator:

C++




// C++ Program to demonstrate the working of modulo operator
#include <iostream>
 
using namespace std;
 
// Driver code
int main(void)
{
    int x, y;
 
    int result;
 
    x = 3;
    y = 4;
 
    // using modulo operator
    result = x % y;
    cout << result << endl;
 
    result = y % x;
    cout << result << endl;
 
    // for different values
    x = 4;
    y = 2;
 
    result = x % y;
    cout << result;
 
    return 0;
}
 
//    This code is contributed by Mayank Tyagi


C




// C Program to illustrate the working of modulo operator
#include <stdio.h>
 
int main(void)
{
    int x, y;
 
    int result;
 
    x = 3;
    y = 4;
    // using modulo operator
    result = x % y;
    printf("%d", result);
 
    result = y % x;
    printf("\n%d", result);
 
    // for different values
    x = 4;
    y = 2;
    result = x % y;
    printf("\n%d", result);
 
    return 0;
}


Restrictions on the Modulo Operator

The modulo operator has few restrictions or limitations on it. The % modulus 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 an error.

Example 1: C/C++ program to demonstrate the restrictions of the modulo operator.

C++




// C++ Program to demonstrate the restrictions of modulo
// operator
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    float x, y;
 
    x = 2.3;
    y = 1.5;
 
    // modulo for floating point values
    result = x % y;
    cout << result;
 
    return 0;
}
 
// This code is contributed by Harshit Srivastava


C




// C Program to illustrate the working of modulo operator
#include <stdio.h>
 
int main(void)
{
    float x, y;
 
    float result;
 
    x = 2.3;
    y = 1.5;
 
    // modulo for floating point values
    result = x % y;
    printf("%f", result);
 
    return 0;
}


Output

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;
^

Modulo Operator for Negative Operands

The sign of the result for the modulo operator is machine-dependent for negative operands, as the action takes as a result of underflow or overflow. 

Example 2: C/C++ program to demonstrate the modulo operator for negative operands.

C++




// C++ Program to demonstrate the working of the modulo
// operator for negative operands
#include <iostream>
using namespace std;
 
// Driver code
int main(void)
{
    int x, y;
 
    int result;
 
    x = -3;
    y = 4;
 
    // modulo for negative operands
    result = x % y;
    cout << result << endl;
 
    x = 4;
    y = -2;
    result = x % y;
    cout << result << endl;
 
    x = -3;
    y = -4;
    result = x % y;
    cout << result;
 
    return 0;
}
 
// This code is contributed by Harshit Srivastava


C




// C Program to illustrate the working of the modulo
// operator with negative operands
#include <stdio.h>
 
int main(void)
{
    int x, y;
 
    int result;
 
    x = -3;
    y = 4;
 
    // modulo for negative operands
    result = x % y;
    printf("%d", result);
 
    x = 4;
    y = -2;
    result = x % y;
    printf("\n%d", result);
 
    x = -3;
    y = -4;
    result = x % y;
    printf("\n%d", result);
 
    return 0;
}


Output

-3
0
-3

Note: The return value in this case is compiler dependent.

FAQs on Modulo Operator

Q1. Define mod.

Answer:

In C/C++ programming languages, mod refers to the mathematical operation in which one number is divided by another, and the remainder is returned.

It can be performed using modulo operator (%).

Q2. What is mod arithmetic?

Answer:

Mod arithmetic refers to the process in which a number keeps wrapping around a certain point in such a way that it is always less than that certain point. For example,

Consider the number n = 10 and the point p = 20.
When we increment n 10 times, it will be n = 20 but in modular arithmetic, it should ways be smaller that the specified point.

One way to do that is to use modulo operator as:

n++;
n = n % p;

To learn more about modular aritimatic, refer to the article – Modular Arithmatic

Q3. What is the difference between modulo and divide operator?

Answer:

The major difference between modulo and division operator is that:

  • Modulo Operator (%) returns the remainder after dividing one number with other.
  • Divide Operator (/) returns the quotient after dividing one number with other.


Similar Reads

deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
Operator Overloading '&lt;&lt;' and '&gt;&gt;' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
Why overriding both the global new operator and the class-specific operator is not ambiguous?
The below section deals about overload resolution as it helps in the fundamentals of overloading and overriding. Predict the output: C/C++ Code #include &lt;iostream&gt; using namespace std; class Gfg { public: void printHello() { cout &lt;&lt; &quot;hello gfg-class specific&quot; &lt;&lt; endl; } }; void printHello() { cout &lt;&lt; &quot;hello gf
5 min read
vector::operator= and vector::operator[ ] in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::operator=This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new
4 min read
Minimum product modulo N possible for any pair from a given range
Given three integers L, R, and N, the task is to find the minimum possible value of (i * j) % N, where L ? i &lt; j ? R. Examples: Input: L = 2020, R = 2040, N = 2019Output: 2Explanation: (2020 * 2021) % 2019 = 2 Input: L = 15, R = 30, N = 15Output: 0Explanation: If one of the elements of the pair is 15, then the product of all such pairs will be d
5 min read
Logical Not ! operator in C with Examples
! is a type of Logical Operator and is read as "NOT" or "Logical NOT". This operator is used to perform "logical NOT" operation, i.e. the function similar to Inverter gate in digital electronics. Syntax: !Condition // returns true if the conditions is false // else returns false Below is an example to demonstrate ! operator: Example: // C program t
1 min read
ios operator() function in C++ with Examples
The operator() method of ios class in C++ is used to any error flag of this stream is set. This includes the failbit or the badbit. Syntax: operator void*() const; Parameters: This method does not accept any parameter. Return Value: This method returns a null pointer if any error bit is set of this stream. Example 1: // C++ code to demonstrate // t
1 min read
ios operator() function in C++11 with Examples
The operator() method of ios class in C++11 is used to any error flag of this stream is set. This includes the failbit or the badbit. Syntax: explicit operator bool() const; Parameters: This method does not accept any parameter. Return Value: This method returns false if any error bit is set of this stream, else true. Example 1: // C++ code to demo
1 min read
ios operator !() function in C++ with Examples
The operator!() method of ios class in C++ is used to any error flag of this stream is set. This includes the failbit or the badbit. Syntax: bool operator!() const; Parameters: This method does not accept any parameter. Return Value: This method returns true if any error bit is set of this stream, else false. Example 1: // C++ code to demonstrate /
1 min read
Arrow operator -&gt; in C/C++ with Examples
An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below. Syntax: (pointer_name)-&gt;(variable_name) Operation: The -&gt; operator in C or C++ gives the val
4 min read
typeid operator in C++ with Examples
typeid is an operator in C++. It is used where the dynamic type or runtime type information of an object is needed.It is included in the &lt;typeinfo&gt; library. Hence inorder to use typeid, this library should be included in the program.The typeid expression is an lvalue expression. Syntax: typeid(type); OR typeid(expression); Parameters: typeid
3 min read
Operands for sizeof operator
The sizeof operator is used to return the size of its operand, in bytes. This operator always precedes its operand. The operand either may be a data-type or an expression. Let's look at both the operands through proper examples. type-name: The type-name must be specified in parentheses. sizeof(type - name) Let's look at the code: C/C++ Code #includ
2 min read
sizeof operator in C
Sizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to compute the size of its operand. The result of sizeof is of the unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data type, including primitive types such as integer and floating-point types, pointer types, or com
3 min read
C++ | Operator Overloading | Question 10
How can we restrict dynamic allocation of objects of a class using new? (A) By overloading new operator (B) By making an empty private new operator. (C) By making an empty private new and new[] operators (D) By overloading new operator and new[] operators Answer: (C) Explanation: If we declare new and [] new operators, then the objects cannot be cr
1 min read
C++ | Operator Overloading | Question 2
Which of the following operators cannot be overloaded (A) . (Member Access or Dot operator) (B) ?: (Ternary or Conditional Operator ) (C) :: (Scope Resolution Operator) (D) .* (Pointer-to-member Operator ) (E) All of the above Answer: (E) Explanation: See What are the operators that cannot be overloaded in C++?Quiz of this Question
1 min read
C++ | Operator Overloading | Question 3
Which of the following operators are overloaded by default by the compiler in every user defined classes even if user has not written? 1) Comparison Operator ( == ) 2) Assignment Operator ( = ) (A) Both 1 and 2 (B) Only 1 (C) Only 2 (D) None of the two Answer: (C) Explanation: Assign operator is by default available in all user defined classes even
1 min read
C++ | Operator Overloading | Question 4
Which of the following operators should be preferred to overload as a global function rather than a member method? (A) Postfix ++ (B) Comparison Operator (C) Insertion Operator &lt;&lt; (D) Prefix++ Answer: (C) Explanation: cout is an object of ostream class which is a compiler defined class. When we do "cout &lt;&lt; obj&quot; where obj is an obje
1 min read
C++ | Operator Overloading | Question 6
Predict the output #include&lt;iostream&gt; using namespace std; class A { int i; public: A(int ii = 0) : i(ii) {} void show() { cout &lt;&lt; i &lt;&lt; endl; } }; class B { int x; public: B(int xx) : x(xx) {} operator A() const { return A(x); } }; void g(A a) { a.show(); } int main() { B b(10); g(b); g(20); return 0; } (A) Compiler Error (B) 10 2
1 min read
C++ | Operator Overloading | Question 7
Output of following program? #include &lt;iostream&gt; using namespace std; class Test2 { int y; }; class Test { int x; Test2 t2; public: operator Test2 () { return t2; } operator int () { return x; } }; void fun ( int x) { cout &lt;&lt; &quot;fun(int) called&quot;; } void fun ( Test2 t ) { cout &lt;&lt; &quot;fun(Test 2) called&quot;; } int main()
1 min read
C++ | Operator Overloading | Question 10
Predict the output? #include&lt;stdlib.h&gt; #include&lt;stdio.h&gt; #include&lt;iostream&gt; using namespace std; class Test { int x; public: void* operator new(size_t size); void operator delete(void*); Test(int i) { x = i; cout &lt;&lt; &quot;Constructor called \n&quot;; } ~Test() { cout &lt;&lt; &quot;Destructor called \n&quot;; } }; void* Test
2 min read
C++ | Operator Overloading | Question 9
#include&lt;iostream&gt; using namespace std; class Point { private: int x, y; public: Point() : x(0), y(0) { } Point&amp; operator()(int dx, int dy); void show() {cout &lt;&lt; &quot;x = &quot; &lt;&lt; x &lt;&lt; &quot;, y = &quot; &lt;&lt; y; } }; Point&amp; Point::operator()(int dx, int dy) { x = dx; y = dy; return *this; } int main() { Point p
1 min read
C++ | Operator Overloading | Question 10
Which of the following operator functions cannot be global, i.e., must be a member function. (A) new (B) delete (C) Conversion Operator (D) All of the above Answer: (C) Explanation: new and delete can be global, see following example. #include #include #include using namespace std; class Myclass { int x; public: friend void* operator new(size_t siz
1 min read
array::operator[ ] in C++ STL
Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::operator[] This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only diffe
2 min read
list::operator= in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::operator= This operator is used to assign new contents to the container by replacing the exis
2 min read
forward_list::operator= in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward lists are useful than other containers for insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from the list by the fact that forward list keeps track of the location of only next element while lis
2 min read
map::operator[] in C++ STL
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. map::operator[] This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at(
2 min read
multiset::operator= in C++ STL
Multisets are a type of associative containers similar to set, with an exception that multiple elements can have same values. multiset::operator= This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new contents.Syntax : multisetname1 = (multisetname2) Parameter
3 min read
multimap::operator= in C++ STL
multimap::operator= is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new contents. Syntax:- multimap1 = (multimap2) Parameters : Another container of the same type. Result : Assign the contents of the container passed as parameter to the container written on left side of
2 min read
unordered_map operator= in C++ STL
The ‘=’ is an operator in C++ STL which copies (or moves) an unordered_map to another unordered_map and unordered_map::operator= is the corresponding operator function. There are three versions of this function. The first version takes reference of an unordered_map as an argument and copies it to an unordered_map. The second version performs a move
2 min read
unordered_multiset operator = in C++ STL
The ‘=’ is an operator in C++ STL which copies (or moves) an unordered_multiset to another unordered_multiset and unordered_multiset::operator= is the corresponding operator function. There are three versions of this function: The first version takes reference of an unordered_multiset as an argument and copies it to an unordered_multiset. Syntax:um
2 min read
Practice Tags :