Suppose p is an arithmetic expression written in postfix notation. The following algorithm, which user a STACK to held operands, evaluates P. Algorithm This algorithm finds the value of an arithmetic expression P written in postfix notation
Not that, when step 5 is executed, There should only be one number on STACK.
ABC+*DE/- a=5, B=6,c=2,D=12,E=4
Symbol scanned | STACK |
|
5 |
|
5 6 |
|
5 6 2 |
|
5 8 |
|
40 |
|
40 12 |
|
40 12 4 |
|
40 3 |
|
37 |
#include <stdio.h>
#include <conio.h>
#include <string.h>
char postfix[20];
int stack[20];
int top = -1;
void get_postfix_expr() {
printf("Enter the postfix expression: ");
}
switch(postfix[i]) {
case '-':
stack[top] = B - A;
top--;
break;
case '*':
stack[top-1] = B * A;
top--;
break;
case '/':
stack[top-1] = B / A;
top--;
break;
}
void calculate() {
int i, A, B;
for (i = 0; postfix[i] != '\0'; i++) {
if (postfix[i] >= '0' && postfix[i] <= '9') {
stack[++top] = postfix[i] - '0';
} else {
B = stack[top--];
A = stack[top--];
switch(postfix[i]) {
case '+':
stack[++top] = A + B;
break;
case '-':
stack[++top] = B - A;
break;
case '*':
stack[++top] = B * A;
break;
case '/':
stack[++top] = B / A;
break;
}
}
}
}
void display() {
printf("Result = %d", stack[top]);
}
int main() {
clrscr();
get_postfix_expr();
calculate();
display();
return 0;
}
Enter the postfix expression: ABC+*DE/-
Enter the value of A: 5
Enter the value of B: 6
Enter the value of C: 2
Enter the value of D: 1
The calculated value is: 33
ABC+*DE/-
is entered as input.calculate()
function evaluates the postfix expression and pushes the result onto the stack.display()
function prints the top element of the stack, which is the calculated value of the postfix expression.You liked the article?
Like: 0
Vote for difficulty
Current difficulty (Avg): Medium
TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.