-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp6StackApplicationPartA.cpp
More file actions
56 lines (54 loc) · 1.34 KB
/
p6StackApplicationPartA.cpp
File metadata and controls
56 lines (54 loc) · 1.34 KB
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
// Design, Develop and Implement a Program for the following Stack Applications a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
#include <iostream>
#include <stack>
#include <cmath>
using namespace std;
// Function to evaluate postfix expression
int evaluatePostfix(string exp)
{
stack<int> s;
for (char ch : exp)
{
if (isdigit(ch))
{
s.push(ch - '0'); // Convert char to int
}
else
{
int val2 = s.top();
s.pop();
int val1 = s.top();
s.pop();
switch (ch)
{
case '+':
s.push(val1 + val2);
break;
case '-':
s.push(val1 - val2);
break;
case '*':
s.push(val1 * val2);
break;
case '/':
s.push(val1 / val2);
break;
case '%':
s.push(val1 % val2);
break;
case '^':
s.push(pow(val1, val2));
break;
}
}
}
return s.top();
}
int main()
{
string postfixExp;
cout << "Enter postfix expression: ";
cin >> postfixExp;
cout << "Result: " << evaluatePostfix(postfixExp) << endl;
return 0;
}