Switch example with do while
Switch allows selection among multiple sections of the code depending on the value in the switch statement.
main() function uses a do while loop to call mainFunction() again and again.
mainFunction() calls the switchFunction().
switchFunction() takes 3 parameters:
num1 takes the first number.
num2 takes the second number.
operation takes the operation to be performed on both numbers.
Following code demonstrates basic operations on 2 integer values using switch statement.
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
void switchFunction(double num1,double num2,char operation)
{
switch(operation)
{
case '+':{cout<<num1<<" + "<<num2<<" = "<<num1+num2<<endl;break;}
case '-':{cout<<num1<<" - "<<num2<<" = "<<num1-num2<<endl;break;}
case '*':{cout<<num1<<" * "<<num2<<" = "<<num1*num2<<endl;break;}
case '/':{cout<<num1<<" / "<<num2<<" = "<<num1/num2<<endl;break;}
case '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;
break;
}
default:
cerr<<"NOT A VALID OPERATION"<<endl;
}
}
void mainFunction()
{
double num1=0,num2=0;
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;
switchFunction(num1,num2,operation);
}
int main()
{
char option;
do
{
system("cls");
mainFunction();
cout<<"WANNA CONTINUE AGAIN FOR NEW INPUT (Y/N) ? ";
cin>>option;
}while(option=='Y'|option=='y');
_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
WANNA CONTINUE AGAIN FOR NEW INPUT (Y/N) ?
Also visit related articles
0 comments:
Post a Comment