modulus operator - Newbie Question

Discussion in 'Mac Programming' started by sparkrulez, Aug 28, 2010.

  1. sparkrulez macrumors newbie


    Aug 20, 2010

    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!

  2. gnasher729 macrumors P6


    Nov 25, 2005
    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.
  3. chown33 macrumors 604

    Aug 9, 2009
    Sailing beyond the sunset
    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.
  4. sparkrulez thread starter macrumors newbie


    Aug 20, 2010
    Thank you

    I appreciate the help and the recommendations. :)

Share This Page