The modulus operator

The modulus operator (also informally known as the *remainder operator*) is an operator that returns the remainder after doing an integer division. For example, 7 / 4 = 1 remainder 3. Therefore, 7 % 4 = 3. As another example, 25 / 7 = 3 remainder 4, thus 25 % 7 = 4. Modulus only works with integer operands.

Modulus is most useful for testing whether a number is evenly divisible by another number: if *x % y* evaluates to 0, then we know that *x* is evenly divisible by *y*.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> int main() { std::cout << "Enter an integer: "; int x{}; std::cin >> x; std::cout << "Enter another integer: "; int y{}; std::cin >> y; std::cout << "The remainder is: " << x % y << '\n'; if ((x % y) == 0) std::cout << x << " is evenly divisible by " << y << '\n'; else std::cout << x << " is not evenly divisible by " << y << '\n'; return 0; } |

Here are a couple runs of this program:

Enter an integer: 6 Enter another integer: 3 The remainder is: 0 6 is evenly divisible by 3

Enter an integer: 6 Enter another integer: 4 The remainder is: 2 6 is not evenly divisible by 4

Modulus with negative numbers

The modulus operator can also work with negative operands. As of C++11, `x % y`

always returns results with the sign of *x*.

Running the above program:

Enter an integer: -6 Enter another integer: 4 The remainder is: -2 -6 is not evenly divisible by 4

Enter an integer: 6 Enter another integer: -4 The remainder is: 2 6 is not evenly divisible by -4

In both cases, you can see the remainder takes the sign of the first operand.

Warning

Prior to C++11, modulus with a negative operand could result in either a positive or negative result. This was made predictable in C++11.

Where’s the exponent operator?

You’ll note that the *^* operator (commonly used to denote exponentiation in mathematics) is a *Bitwise XOR* operation in C++ (covered in lesson O.3 -- Bit manipulation with bitwise operators and bit masks). C++ does not include an exponent operator.

To do exponents in C++, #include the <cmath> header, and use the pow() function:

1 2 3 |
#include <cmath> double x{ std::pow(3.0, 4.0) }; // 3 to the 4th power |

Note that the parameters (and return value) of function pow() are of type double. Due to rounding errors in floating point numbers, the results of pow() may not be precise (even if you pass it integers or whole numbers).

If you want to do integer exponentiation, you’re best off using your own function to do so. The following function implements integer exponentiation (using the non-intuitive “exponentiation by squaring” algorithm for efficiency):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <cstdint> // for std::int_fast64_t // note: exp must be non-negative std::int_fast64_t pow(int base, int exp) { std::int_fast64_t result{ 1 }; while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } |

Don’t worry if you don’t understand how this function works -- you don’t need to understand it in order to call it.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <cstdint> // for std::int_fast64_t // note: exp must be non-negative std::int_fast64_t powint(int base, int exp) { std::int_fast64_t result{ 1 }; while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } int main() { std::cout << powint(7, 12); // 7 to the 12th power return 0; } |

Produces:

13841287201

Warning

In the vast majority of cases, integer exponentiation will overflow the integral type. This is likely why such a function wasn’t included in the standard library in the first place.

Quiz time

Question #2

Write a program that asks the user to input an integer, and tells the user whether the number is even or odd. Write a function called isEven() that returns true if an integer passed to it is even, and false otherwise. Use the modulus operator to test whether the integer parameter is even.Hint: You’ll need to use if statements and the comparison operator (==) for this program. See lesson 4.9 -- Boolean values if you need a refresher on how to do this.

Your program should match the following output:

Enter an integer: 5 5 is odd

5.4 -- Increment/decrement operators, and side effects |

Index |

5.2 -- Arithmetic operators |

So can we use the pow() function for integers?? Because I try this function for integers and it worked

`std::pow` only operates on floating point numbers.

I did it different than you but ended up with the same results, is this fine? I am also a lot more comfortable with the way I did when compared to the way you did it, is that bad and should I try to change that mindset? I would also like to thank you for this book as I'm going to call it, it has been a God send.

I was examining question 2 again and I just realized you requested that we make a function that returns true or false, I missed that. Never mind my bit of code.

Your code still shows that you understand the concepts asked for in this quiz. If your program prints anything, it's good to print a line feed (\n) at the end to prevent mixing output with other programs.

Thank you so much for your feedback. I normally do put '\n' at the end of my prints but I often forget to, this was one of those cases.

A little bit shorter but just as good?

You're converting from int to bool. It does what it should, but can be harder to read than an explicit conversion via `==`.

I had the same idea.

Would this code be slower than the quiz solution, or is it just a matter of clarity?

It will probably produce exactly the same binary as the quiz. Your compiler is great at optimizing simple things. Do what you find easier to read, I prefer the comparison to 0.

Thanks for the well-structured material!

My approach:

hi Raul!

`isEven` isn't supposed to print anything, but return false/true depending on whether or not `x` is even. Try to implement it in a way that `main` does the printing.

Thanks for the intervention, nascardriver.

That's it, good job! `isEven` can be simplified even further, have a look at the solution for an explanation.

This is my way of solving this task:

Hi!

You're not using the return value of `isTrue`. Declare it `void`.

`std::cin >> x` should be on its own line for better readability.

If your program prints anything, the last thing it prints should be a line feed.

"isTrue" is a poor name, it doesn't describe what the function does.

How to fix this code? 0 appeared on the result. Thanks.

`isEven` always returns `false` (Line 11). It appears you don't want to use the return value at all. Declare `isEven` `void` and don't print in line 20.

Return values are covered in lesson 2.2.

Thanks, Nascardriver. I should read carefully and slowly.

Why do we need to write std:: for pow? Cause it allows us to use it without std. Both codes work.

You forgot to include the word 'evenly' in the code output examples.

Fixed. Thanks!