# Basic Calculator in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we want to create one basic calculator that will find the basic expression result. The expression can hold opening and closing parentheses, plus or minus symbol and empty spaces.

So if the string is like “5 + 2 - 3”, then the result will be 7

To solve this, we will follow these steps −

• ret := 0, sign := 1, num := 0, n := size of s

• Define one stack st

• for initializing i := 0, when i < n, increase i by 1 do −

• Define an array x = s of size i

• if x >= '0' and x <= '9', then,

• num = num * 10

• num = num + (x - '0')

• Otherwise when x is same as '(', then −

• ret = ret + (sign * num)

• insert ret into st

• ret := 0, sign := 1, num := 0

• Otherwise when x is same as ')', then −

• ret = ret + (sign * num), sign := 1, num := 0

• ret = ret * top element of st

• delete item from st

• ret = ret + top element of st

• delete item from st

• Otherwise when x is same as '+', then −

• ret = ret + (sign * num), sign := 1, num := 0

• Otherwise when x is same as '-', then −

• ret = ret + (sign * num), sign := - 1, num := 0

• if num is non-zero, then,

• ret = ret + sign * num

• return ret

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int calculate(string s) {
int ret = 0;
int sign = 1;
int num = 0;
int n = s.size();
stack <int> st;
for(int i = 0; i < n; ++i){
char x = s[i];
if(x >= '0' && x <= '9'){
num *= 10;
num += (x - '0');
}
else if(x == '('){
ret += (sign * num);
st.push(ret);
st.push(sign);
ret = 0;
sign = 1;
num = 0;
}
else if(x == ')'){
ret += (sign * num);
sign = 1;
num = 0;
ret *= st.top();
st.pop();
ret += st.top();
st.pop();
}
else if(x == '+'){
ret += (sign * num);
sign = 1;
num = 0;
}
else if(x == '-'){
ret += (sign * num);
sign = -1;
num = 0;
}
}
if(num){
ret += sign * num;
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.calculate("5 + 2 - 3"));
}

## Input

"5 + 2 - 3"

## Output

4