If-else-if statement example
If-else-if allows selection among multiple sections of the code depending on the condition.
Same thing can be done by using Switch statement:
Following code demonstrates basic operations on 2 integer values using if-else-if statement.
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
int main()
{
double num1,num2;
char operation;
cout<<"ENTER FIRST NUMBER > ";
cin>>num1;
cout<<"ENTER SECOND NUMBER > ";
cin>>num2;
cout<<"ENTER OPERATION"<<endl;
cout<<"+ FOR ADDITION"<<endl;
cout<<"- FOR ADDITION"<<endl;
cout<<"* FOR ADDITION"<<endl;
cout<<"/ FOR ADDITION"<<endl;
cout<<"A FOR ADDITION"<<endl;
cin>>operation;
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;
_getche();
return 0;
}
Output
ENTER FIRST NUMBER > 6
ENTER SECOND NUMBER > 5
ENTER OPERATION
+ FOR ADDITION
- FOR ADDITION
* FOR ADDITION
/ FOR ADDITION
A FOR ADDITION
A
6 + 5 = 11
6 - 5 = 1
6 * 5 = 30
6 / 5 = 1.2
0 comments:
Post a Comment