![]() ![]() | ||||
![]() ![]() |
Implementing
Modulus 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. Example:#include <iostream> using namespace std; int main() { int some_value; std::cout << "Enter a value: "; std::cin >> some_value; if ( some_value % 2 == 0 ) { std::cout << some_value << " is an even number" << endl; } else { 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. Example:some_value = 4 4 % 2 == 22 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. ----- |
| ||
|