This statement is also used for decision making. Here key word is switch followed by control variable and followed by it’s block.
In the block of switch statement multiple cases are used and each ends with break statement this is also called as early exit loop.
Out of all the cases only that case will run whose value matches with the control variable.
/* Program to make a calculator using switch statement and apply such condition that it will terminate by the users wish */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int add,sub,mul,mod,a,b,n;
float div;
cout<<"\n Enter any two values";
cin>>a>>b;
do
{
cout<<"\n Enter any operation:";
cout<<"\n 1: Addition\n 2: Subtraction\n 3: Multiplication\n 4: Division\n 5: Remainder\n 6:Exit\n";
cin>>n;
switch(n)
{
case 1:
{
add=a+b;
cout<<"\n\n Addition of "<<a<<" and "<<b<<" is "<<add;
break;
}
case 2:
{
sub=a-b;
cout<<"\n\n Subtraction of "<<a<<" and "<<b<<" is "<<sub;
break;
}
case 3:
{
mul=a*b;
cout<<"\n\n Multiplication of "<<a<<" and "<<b<<" is "<<mul;
break;
} }
case 4:
{
div=float(a)/b;
cout<<"\n\n Division of "<<a<<" and "<<b<<" is "<<div;
break;
}
case 5:
{
mod=a%b;
cout<<"\n\n Remainder of "<<a<<" and "<<b<<" is "<<mod;
break;
}
case 6:
exit(0);
default:
cout<<"\n Enter correct operation";
}
}
while(n=6);
getch();
}
No comments:
Post a Comment