How can I check if a number is even or not? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

22nd Jul 2017, 8:14 AM
Győrfy Balázs
Győrfy Balázs - avatar
5 Answers
+ 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.
22nd Jul 2017, 8:18 AM
ChessMaster
ChessMaster - avatar
+ 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!
21st Apr 2018, 7:01 AM
Fox
Fox - avatar
+ 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 }
22nd Jul 2017, 10:55 AM
visph
visph - avatar
+ 1
Man you are amazing,Thank you :)
22nd Jul 2017, 8:33 AM
Győrfy Balázs
Győrfy Balázs - avatar
0
use if or else
23rd Jul 2017, 2:27 AM
Gabrielle Cristine
Gabrielle Cristine - avatar