Table of Contents
The modulus operator (%) returns the remainder after dividing one integer by another. It is commonly used to determine whether a number is even or odd, extract digits from a number, and perform cyclic operations.
The modulus operator is defined only for integral data types such as int, char, short, and long. It cannot be applied directly to floating-point operands.
Source Code #
#include <iostream>
int main()
{
int dividend = 25;
int divisor = 4;
int remainder = dividend % divisor;
std::cout << "Dividend : " << dividend << '\n';
std::cout << "Divisor : " << divisor << '\n';
std::cout << "Remainder: " << remainder << '\n';
return 0;
}
Output #
Dividend : 25
Divisor : 4
Remainder: 1
Explanation #
- The modulus operator (
%) computes the remainder after integer division. dividend % divisorreturns the remainder obtained whendividendis divided bydivisor.- Both operands of the modulus operator must be of integral data types.
- The result is assigned to the variable
remainder. - The modulus operator is frequently used to determine divisibility, such as checking whether a number is even or odd.
- Using the modulus operator with a divisor of zero results in undefined behavior.
std::coutdisplays the operands and the calculated remainder.return 0;terminates the program successfully.