This site requires JavaScript, please enable it in your browser!
Greenfoot back
Kartoffelbrot
Kartoffelbrot wrote ...

2013/7/28

Even numbers

Kartoffelbrot Kartoffelbrot

2013/7/28

#
How can I check wether an integer is even or not?
danpost danpost

2013/7/28

#
Use the modulus operation:
 if ( value % 2 == 0 ) // executes when 'value' is even
if ( value % 2 == 1) // executes when 'value' is odd
Kartoffelbrot Kartoffelbrot

2013/7/28

#
What does % do exactly? Does it remove (in this case) 2 as long as it is possible to don't get negative?
danpost danpost

2013/7/28

#
That is one way of looking at it.
int value = Greenfoot.getRandomNumber(100);
int remainder = value % 2;
// is equivalent to
int value = Greenfoot.getRandomNumber(100);
int remainder = value - (value/2)*2;
Either way, what you are doing is dividing by some number and after dropping the number of times the number goes into it, return what is left (the remainder). It works with negative numbers as well; the number returned will be the negative value of what the positive counterpart returns.
Kartoffelbrot Kartoffelbrot

2013/7/28

#
thanks
You need to login to post a reply.