Switch statement in C++ is a Compact and easy alternative to If Else Statement as explained earlier in this blog. We will now use switch statement to create a mini calculator similar to one we have made earlier using
if-else statement.
Program
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
char sign; int a,b,c;
cout<<"Enter the First number :'<<endl;
cin>>a;
cout<<"Enter the Second number :"<<endl;
cin>>b;
cout<<"Press + to add"<<endl<<"Press - to subtract"<<endl<<"Press * to multiply"<<endl<<"Press / to divide"<<endl;
cin>>sign;
switch(sign)
{
case'+' : c=a+b;
cout<<"Sum of A and B is : "<<c;
break;
case'-' : c=a-b;
cout<< "Difference of A and B is : "<<c;
break;
case'*' : c=a*b;
cout<<"Product of A and B is :"<<c;
break;
case'/': c=a/b;
cout<<"Dividing A into B Parts is :"<<c;
break;
default: cout<<"Invalid Opration Selected";
}
getch();
}
if-else statement.
Program
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
char sign; int a,b,c;
cout<<"Enter the First number :'<<endl;
cin>>a;
cout<<"Enter the Second number :"<<endl;
cin>>b;
cout<<"Press + to add"<<endl<<"Press - to subtract"<<endl<<"Press * to multiply"<<endl<<"Press / to divide"<<endl;
cin>>sign;
switch(sign)
{
case'+' : c=a+b;
cout<<"Sum of A and B is : "<<c;
break;
case'-' : c=a-b;
cout<< "Difference of A and B is : "<<c;
break;
case'*' : c=a*b;
cout<<"Product of A and B is :"<<c;
break;
case'/': c=a/b;
cout<<"Dividing A into B Parts is :"<<c;
break;
default: cout<<"Invalid Opration Selected";
}
getch();
}