Search code examples
carithmetic-expressions

What is the purpose of the % in the following code?


I am making a snake game for my university assignment. In C. Now, I know this isn't the ideal langiage for the task but it's my assignment. I found an example code anda am currently rewriting it / understanding it so I can write my own working code. So far it's an easy ride and it's all coming together but for the life of me I can't figure out why they put a the % in the following lines:

        for (i = 1; i <= 1 + rand() % 10; i++)
            food.x = 12 + rand() % (68 - 12);
        for (i = 1; i <= 1 + rand() % 10; i++)
            food.y = 12 + rand() % (28 - 12);

For context this is in the function for creating food in the playing field. I understand the rand thing and adding these numbers (it's my playing field size) but why put a modulo division? What does it achieve?


Solution

  • % is the modulo operator, mostly used like in this scenario to limit a value see modulo operator wiki

    f.e. 1 + rand() % 10 means the value will be 1 + [0..9] - so max is 10. [0..9] is the random number modulo 10, and will be a number between 0 and 9.