C++

How Does mod Operator Work in C++

Modulus operator, commonly referred to as mod is an operator widely used in programming languages, including C++. This operator is denoted with the sign (%) and is utilized for finding remainder when we have to divide a number with another number.

Follow this guide to learn about mod operator working in C++.

How Does mod Operator Work in C++

Whenever we have to divide a number by another number in an arithmetic operation, it will produce a remainder. That remainder could be zero or non-zero value. The zero value occurs if a number is completely divisible by the other number like 2%2 outputs 0 as a remainder, while 8%3 outputs 2.

The general syntax to use the mod operator in C++ is shown below:

n1 % n2

 
Where n1 could be any number that can be divisible with any number n2.

Let’s implement a simple example of using the mod operator in C++:

#include <iostream>
using namespace std;

int main()
{
    int a = 8, b = 3;
    int result;
    result = a % b;
    cout << "The remainder is: " << result << endl;
    return 0;
}

 
In the above example, we used two integer values a and b and the result of the mod operator is stored in the result variable, which is then printed using cout.

Output

 

You can also use the mod operator to find whether the number is even or add. Here is the example for such a case.

#include <iostream>
using namespace std;
int main()
{
    int n1, n2;
    cout << "Please enter the first number:" << endl;
    cin >> n1;
    cout << "Please enter the second number:" << endl;
    cin >> n2;
    if (n1 % 2 == 0)
        cout << n1 << " is even" << endl;
    else
        cout << n1 << " is odd" << endl;
    if (n2 % 2 == 0)
        cout << n2 << " is even" << endl;
    else
        cout << n2 << " is odd" << endl;
    return 0;
}

 
In the above code, we use the mod operator by dividing the numbers with the value 2. The remainder is then checked whether it’s even or odd.

Conclusion

In C++, the mod (%) operator seems to calculate the remainder when we divide a number by another number. Its use is simple in C++ programming language and you can follow the above-mentioned examples to learn the use of the mod operator in C++.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.