Determining if a number is either a multiple of ten or within a particular set of ranges

user3419168 picture user3419168 · Apr 28, 2014 · Viewed 26.7k times · Source

I have a few loops that I need in my program. I can write out the pseudo code, but I'm not entirely sure how to write them logically.

I need -

if (num is a multiple of 10) { do this }

if (num is within 11-20, 31-40, 51-60, 71-80, 91-100) { do this }
else { do this } //this part is for 1-10, 21-30, 41-50, 61-70, 81-90

This is for a snakes and ladders board game, if it makes any more sense for my question.

I imagine the first if statement I'll need to use modulus. Would if (num == 100%10) be correct?

The second one I have no idea. I can write it out like if (num > 10 && num is < 21 || etc.), but there has to be something smarter than that.

Answer

Winston Ewert picture Winston Ewert · Apr 28, 2014

For the first one, to check if a number is a multiple of use:

if (num % 10 == 0) // It's divisible by 10

For the second one:

if(((num - 1) / 10) % 2 == 1 && num <= 100)

But that's rather dense, and you might be better off just listing the options explicitly.


Now that you've given a better idea of what you are doing, I'd write the second one as:

   int getRow(int num) {
      return (num - 1) / 10;
   }

   if (getRow(num) % 2 == 0) {
   }

It's the same logic, but by using the function we get a clearer idea of what it means.