+92 332 4229 857 99ProjectIdeas@Gmail.com

Difference between multiple if and if-else-if statement


Difference between multiple if and if-else-if statement
When only 1 section of code is desired to be executed among multiple section of codes,if-else-if is preffered over multiple if statements.
Multiple if statements are preffered in case when more than 1 conditions are to be checked at a time. Multiple if statements are preffered in case like:


#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

int main()
{
       int month = 2;
       int daysInMonth = 29;

              if ( month == 2 )
              {
                     cout << month << endl;

                     if ( daysInMonth == 29 )
                     {
                            cout << "Leap year" << endl;
                     }
              }

       _getche();
       return 0;
}

Following declaration for the below mentioned example
double num1,num2;
char operation;

Multiple If statements example
if(operation=='+')
cout<<num1<<" + "<<num2<<" = "<<num1+num2<<endl;
if(operation=='-')
cout<<num1<<" - "<<num2<<" = "<<num1-num2<<endl;
if(operation=='*')
cout<<num1<<" * "<<num2<<" = "<<num1*num2<<endl;
if(operation=='/')
cout<<num1<<" / "<<num2<<" = "<<num1/num2<<endl;
if(operation=='A')
{
cout<<num1<<" + "<<num2<<" = "<<num1+num2<<endl;
cout<<num1<<" - "<<num2<<" = "<<num1-num2<<endl;
cout<<num1<<" * "<<num2<<" = "<<num1*num2<<endl;
cout<<num1<<" / "<<num2<<" = "<<num1/num2<<endl;
}

If-else-if statements example
if(operation=='+')
cout<<num1<<" + "<<num2<<" = "<<num1+num2<<endl;
else if(operation=='-')
cout<<num1<<" - "<<num2<<" = "<<num1-num2<<endl;
else if(operation=='*')
cout<<num1<<" * "<<num2<<" = "<<num1*num2<<endl;
else if(operation=='/')
cout<<num1<<" / "<<num2<<" = "<<num1/num2<<endl;
else if(operation=='A')
{
cout<<num1<<" + "<<num2<<" = "<<num1+num2<<endl;
cout<<num1<<" - "<<num2<<" = "<<num1-num2<<endl;
cout<<num1<<" * "<<num2<<" = "<<num1*num2<<endl;
cout<<num1<<" / "<<num2<<" = "<<num1/num2<<endl;
}
else
cerr<<"NOT A VALID OPERATION"<<endl;

In the first example (Multiple If statements example), all the if statements are checked and it waste the time and makes the program inefficient, while in the second example (If-else-if statements), if one statement is executed the rest of the following if statements are by passed which reduces the execution time and makes the program efficient.
The choice of which type of if to be selected depends upon the situation.

0 comments: