Calculator using Switch Case in C++
This is a C++ program that asks the user to input an operator and two numbers, and then performs the corresponding arithmetic operation based on the operator using a switch statement. Here's a breakdown of the code:
- char oper; float n1, n2; These lines declare three variables: oper of type char to store the operator, and n1 and n2 of type float to store the two numbers.
- cout<<"\nEnter an operator (+,-,*,/): "; cin>>oper; These lines prompt the user to enter an operator and read the input into the oper variable using the cin function.
- cout<<"\nEnter two numbers: "<<endl; cin>>n1>>n2; These lines prompt the user to enter two numbers and read the input into the n1 and n2 variables using the cin function. Note that endl is used to add a newline after the prompt.
- switch(oper) { ... } This is a switch statement that takes the value of the operv variable and executes the corresponding case. If oper is +, it will execute the code block after case '+'. If oper is -, it will execute the code block after case '-', and so on. If oper doesn't match any of the cases, it will execute the code block after the default case.
- cout<<n1<<" + "<<n2<<" = "<<n1+n2; These are examples of the code block that is executed when the oper variable matches the corresponding case. For example, when oper is +, it will output the sum of n1 and n2 using the + operator.
- return 0; This line ends the program and returns 0 to the operating system to indicate that the program executed successfully.
Source Code
#include<iostream>
using namespace std;
int main()
{
char oper;
float n1, n2;
cout<<"\nEnter an operator (+,-,*,/): ";
cin>>oper;
cout<<"\nEnter two numbers: "<<endl;
cin>>n1>>n2;
switch(oper)
{
case '+':
cout<<n1<<" + "<<n2<<" = "<<n1+n2;
break;
case '-':
cout<<n1<<" - "<<n2<<" = "<<n1-n2;
break;
case '*':
cout<<n1<<" * "<<n2<<" = "<<n1*n2;
break;
case '/':
cout<<n1<<" / "<<n2<<" = "<<n1/n2;
break;
default:
cout<<"Error! The operator is not correct";
break;
}
return 0;
}
To download raw file
Click Here
Output
Enter an operator (+,-,*,/): *
Enter two numbers:
23
21
23 * 21 = 483