# Create a Simple calculator in C++

In this tutorial, we will see the basic implementation of a simple calculator in C++. It includes all the basic operations:

2. Subtraction(-)
3. Multiplication(*)
4. Division(/)
5. Modulo(%)

## How to write code for a simple calculator in C++

• First, we will take input char ch. It will be the operation we want to perform.
• – for subtraction
• / for division
• * for multiplication
• % for modulo i.e remainder of two numbers
• Then we take input for our first number i.e N1.
• And our second number N2.
• else if it is equal to X or x, it means to end up doing calculations i.e stop the calculator.
• else if it is another char which is unidentified like ‘\$’ or ‘#’, it will print invalid operation for it.

Important point while writing code:

While performing division, do check that n2 is not equal to zero. In the case, it equals to zero division cant be performed.

Here, is the code:

```#include <iostream>
using namespace std;

int main(){
char ch;

while(true){
cin>>ch;

if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%'){
int N1,N2;
cin>>N1;
cin>>N2;

if(ch=='+'){
cout<<N1+N2<<endl;
}
else if(ch=='-'){
cout<<N1-N2<<endl;
}
else if(ch=='*'){
cout<<N1*N2<<endl;
}
else if(ch=='/'){
if(N2!=0){
cout<<(double)N1/N2<<endl;
}
else{cout<<"cant divide"<<endl;}
}
else{
if(N2!=0){
cout<<N1%N2<<endl;
}
}
}
else if(ch=='X'||ch=='x'){
break;
}
else{
cout<<"Invalid operation. Try again."<<endl;
}
}
return 0 ;
}
```

INPUT:

```+
5 2
/
94 2
/
5 0
\$
x```

Output:

Try it on your machine. That will be more fun!

This is a basic code using the if-else loop to write a program of a simple calculator in c++ by taking inputs from keyboards. The code could also be written using switch cases.

Also, refer to:

Using vector class without header file in C++