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.

About the Author

has written 38 stories on this site.

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

*

Copyright © 2024 Programmer to Programmer- A website for web programming and mobile application programming tutorials.
Wordpress themes