C++ Modulus Operator
C++ Modulus Operator
In this tutorial, we will learn about the C++ Modulus Operator with examples. The C++ modulus operator is the % symbol. It returns the remainder of the integer division. We can use this operator with integer operands.
Example
13%3 = 13 – (4*3)
= 13 – 12
= 1
13%3 = 1
C++ Program
Let’s write a simple C++ program and use the modulus operator.
//******************************* // C++ Modulus Operator // C++ Tutorials // www.TestingDocs.com //******************************* #include using namespace std; int main() { //Declare integer variables int x = 15; int y = 10; int result = x%y; cout << "x = " << x << endl ; cout << "y = " << y << endl ; cout << "x%y = " << result << endl ; return 0; }
Output
Build and run the program in Code::Blocks. Let’s analyze the program output.
x = 15
y = 10
x%y = 5
The variable x has 15 and the variable y has 10. When we divide 15 with 10 we get 5 as the remainder.
The result of 15%10 or x%y is 5.
#
Let’s look at another example. Let’s assume the following variables:
int x = 12;
int y = 4;
12 is divisible by 4, so we get 12%4 = 0. This is a useful condition to check if the number is divisible by another number.
Exercises
# What would be the output of 16%6?
# Write a simple C++ program to check if a number is divisible by 3. Hint:
if(x%3 ==0)
cout << “The number is divisible by 3 ” << endl ;
—
C++ Tutorials
C++ Tutorials on this website:
https://www.testingdocs.com/c-coding-tutorials/
For more information on the current ISO C++ standard
https://isocpp.org/std/the-standard