-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcalculation.cpp
104 lines (102 loc) · 1.71 KB
/
calculation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include<iostream>
#include<string.h>
using namespace std;
int isOperator(char symbol){
if(symbol=='*'||symbol=='/'){
return 2;
}
else if(symbol=='+'||symbol=='-'){
return 1;
}else{
return 0;
}
}
int isParenthesis(char symbol){
if(symbol=='('){
return 1;
}else if (symbol==')'){
return 2;
}else{
return 0;
}
}
int isOperand(char symbol){
if(isOperator(symbol)==0 && isParenthesis(symbol)==0){
return 1;
}else{
return 0;
}
}
void print(char arr[]){
int i=0;
while(arr[i]!='\0'){
cout<<arr[i];
i++;
}
}
class stack{
int arr[100];
int top_index;
public:
stack(){
top_index=-1;
}
bool isEmpty(){
return(top_index==-1);
}
void push(int s){
top_index++;
arr[top_index]=s;
}
int pop(){
if(!isEmpty()){
int temp=arr[top_index];
top_index--;
return temp;
}
}
int peek(){
if(!isEmpty()){
int temp=arr[top_index];
return temp;
}
}
void display(){
int i;
for(i=0;i<=top_index;i++){
cout<<arr[i]<<endl;
}
}
};
int main(void){
string postexp;
cout<<"Enter the expression: ";
cin>>postexp;
stack s;
int result;
int i=0;
int j=0;
while(postexp[i]!='\0'){
if(isOperand(postexp[i])){
s.push(postexp[i]-'0');
}
else {
int operand2=s.pop();
int operand1=s.pop();
int resultant;
if(postexp[i]=='+'){
resultant=operand1+operand2;
}else if(postexp[i]=='-'){
resultant=operand1-operand2;
}else if(postexp[i]=='*'){
resultant=operand1*operand2;
}else if(postexp[i]=='/'){
resultant=operand1/operand2;
}
s.push(resultant);
}
i++;
}
result=s.pop();
cout<<"Result : "<<result<<endl;
}