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 == 2 2 is an even number, there is no remainder. Now consider this: some_value = 3 3 % 2 == 1.5

 

Bhopal news
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

India website designer web development India php ecommerce developer | Web design India, Ecommerce web design | India web hosting website host india | Windows hosting India web hosting | Software development India | Flash web designer india