PDA

View Full Version : modulus operator - Newbie Question




sparkrulez
Aug 28, 2010, 06:48 PM
Hello,

I hope I am posting this in the right area, if not then please direct me to the correct area.

I just started learning Objective C and I can't seem to find a good explanation of the % Modulus Operator.

Here's an example.

a = 2
b = 3
c = a % b

Answer is c = 2.

I don't understand the mathimatical equation that the modulus operator represents. I apologize for the newbie question.


Thank you in advance!

Spark



gnasher729
Aug 28, 2010, 07:23 PM
Hello,

I hope I am posting this in the right area, if not then please direct me to the correct area.

I just started learning Objective C and I can't seem to find a good explanation of the % Modulus Operator.

Here's an example.

a = 2
b = 3
c = a % b

Answer is c = 2.

I don't understand the mathimatical equation that the modulus operator represents. I apologize for the newbie question.


Thank you in advance!

Spark

1. Google for "n1256.pdf". That's the latest free draft of the C Standard. That means _everything_ about C is in there, including the modulo operator (and you can look up modulus as well, which is something completely different :-) If you are serious about programming, get it.

2. a % b is the division remainder. 20 divided by 3 equals 6 with a remainder of 2. Therefore 20 / 3 -> 6, and 20 % 3 -> 2.

3. To get a feeling for it, write a loop that prints i and i % 7, say for i = 1 to 100.

chown33
Aug 28, 2010, 07:30 PM
3. To get a feeling for it, write a loop that prints i and i % 7, say for i = 1 to 100.

An excellent suggestion. It's not really possible to see its effect on a single example. I also suggest printing i / 7 at the same time, so one can see how integer division (also called truncating division) works.

One can think of it as the remainder after division, or as "circular arithmetic", such as with a clock.
http://en.wikipedia.org/wiki/Modular_arithmetic

sparkrulez
Aug 28, 2010, 08:58 PM
I appreciate the help and the recommendations. :-)