How to optimize if else statement in a smart way?
In this tutorial i am going to show how can we optimize the if else statement. This method can be used in any programming languages. I am going to show two different ways we can optimize the if else statement.
lets see default if else statement:
if( n % 2 == 0){
result = n + ” is even number”;
}else{
result = n + ” is odd number”;
}
print result;
Method 1:
result = n + ” is odd number”;
if( n % 2 == 0){
result = n + ” is even number”;
}
print result;
In this first method we define result variable as odd number and then use only if statement to alter the result if it is not an odd number. This is a first smart way.
Method 2:
result = ( n % 2 == 0)?n + ” is even number”:n + ” is odd number”;
print result;
This second method is a use of ternary operator. The syntax of ternary operator is conditionCheck?trueStatement:falseStatement.
Recent Comments