I have seen different ways of writing an if statement.
Which one do you prefer and why?
Example 1:
if (val % 2 == 1){output = “Number is odd”;}else{output = “Number is even”;}
Example 2:
if (val % 2 == 1) { output = “Number is odd”; } else { output = “Number is even”; }
Example 3:
if (val % 2 == 1) output = “Number is odd”; else output = “Number is even”;
Example 4:
if (val % 2 == 1){ output = “Number is odd”; } else { output = “Number is even”; }
For cases like this, there’s also the conditional operator:
If you’re definitely going to use an ‘if’ I’d use version 2 or version 4, depending on the rest of your bracing style. (At work I use 4; for personal projects I use 2.) The main thing is that there are braces even around single statements.
BTW, for testing parity it’s slightly quicker to use: