+ 2
How can I check if a number is even or not?
For example if I want to print âdogâ if x is even,how should I do this?
5 RĂ©ponses
+ 9
Try this:
if(x % 2 == 0) {
//Even related code
}
Or:
if(x % 2 != 0) {
//Uneven related code
}
% means what is left over if you divide by the number that comes after it. So for example 34 % 2 = 0. Because 34 / 2 = 17 and 0 is left over. For uneven numbers 1 is left over.
+ 8
Now that you're educated on conditional-statements, perhaps it'd be helpful to look into shorthand versions of conditional statements.
For example ...
> Python:
if x % 2:
print('odd')
else:
print('even')
... can be rewritten like ...
print('odd' if x % 2 else 'even')
> C++:
if (x % 2)
return "odd";
else
return "even";
... can be rewritten like ...
return (x % 2) ? "odd" : "even";
I don't know very much about Java, but I'm sure every language has it's own versions of shorthand-expressions. Be sure to check them out, it's worth it!
+ 4
You can even use the & binary operator, which would be a bit more efficient (basic root operation):
if (x & 1 == 0) {
// even related code
}
+ 1
Man you are amazing,Thank you :)
0
use if or else