Written by RoD
Modulus is a C++ function with many uses. Perhaps the most common use is finding whether or not a variable is odd or even. Modulus can also be used to find multiples of a number. Modulus works by dividing and returning a remainder, if any, of the calculation. This may seem a little confusing to you at the moment, and thatÕs perfectly normal.
Modulus is represented in C++ by the Ō%Ķ symbol. IÕm going to show you a sample program that uses the Modulus function, and then explain it piece by piece, as I think that is the best way to make sense of what I am telling you.
using namespace std;
std::cout << "Enter a value: ";
std::cin >> some_value;
if ( some_value % 2 == 0 )
std::cout << some_value << " is an even number" << endl;
std::cout<< val << " is an odd number" <<<< endl;
Ok everything up to the if statement should make plenty of sense to you by now, and if it doesnÕt you need to consult another tutorial. IÕm going to explain this if statement and what its doing because thatÕs the chunk of this program that pertains to the subject as hand.
if ( some_value % 2 == 0 ) :ĘThis line may look a bit confusing at first, but in a moment its going to make plenty of sense! If the user given value modulus two gives no remainder, then the user given value is even. What this means is that the value given to us by the user, divided by two, had no remainder, which makes it even.
some_value = 4
4 % 2 == 2
2 is an even number, there is no remainder. Now consider this:
some_value = 3
3 % 2 == 1.5
1.5 is odd, it has a remainder. Does it make more sense now? Hopefully it does and you have benefit from this lesson. I look forward to helping you in the future. Feel free to contact me via the message boards as RoD or via my email at Silent_Death17@hotmail.com.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More Web Development Articles
More By Developer Shed