You are on page 1of 6

EXPERIMENT NO.

: 3
Evaluate Postfix Expression using Stack ADT.

NAME: HARSH KISHOR ALASHI


CLASS: SE COMPS
DIVISION: A
BATCH: A1
ROLL NO.: CEA304
AIM: To Evaluate Postfix Expression using Stack ADT.

THEORY:

Evaluation rule of a Postfix Expression states:


While reading the expression from left to right, push the element in the stack if it is an
operand.
Pop the two operands from the stack, if the element is an operator and then evaluate it.
Push back the result of the evaluation. Repeat it till the end of the expression.
Algorithm:
1) Add ) to postfix expression.
2) Read postfix expression Left to Right until ) encountered
3) If operand is encountered, push it onto Stack
[End If]
4) If operator is encountered, Pop two elements
i) A -> Top element
ii) B-> Next to Top element
iii) Evaluate B operator A
push B operator A onto Stack
5) Set result = pop
6) END

Expression: 456*+
Result: 34
PROGRAM:

//CEA304_HARSH KISHOR ALASHI


//EXPERIMENT-3
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SIZE 20
struct stack
{
int top;
int x[SIZE];
} s;
int isEmpty();
char pop();
void push(char);
double eval_postfix(char expr[], int);
int main()
{
char expr[SIZE];
double ans;
int l;
printf("Enter postfix expression: ");
scanf("%s", expr);
l = strlen(expr);
ans = eval_postfix(expr, l);
printf("Answer = %lf", ans);
return 0;
}
int isEmpty()
{
return s.top == -1 ;
}
char pop()
{
if (!isEmpty())
return s.x[s.top--] ;
}
void push(char op)
{
s.x[++s.top] = op;
}
double eval_postfix(char expr[SIZE], int l)
{
expr[l] = ')';
int i = 0;
double res = 0;
for (i = 0; expr[i] != ')'; ++i)
{
if (isdigit(expr[i]))
push(expr[i] - '0');
else
{
int val1 = pop();
int val2 = pop();
switch (expr[i])
{
case '+': push(val2 + val1); break;
case '-': push(val2 - val1); break;
case '*': push(val2 * val1); break;
case '/': push(val2/val1); break;
case '%': push(val2 % val1); break;
}
}
}
return pop();
}

OUTPUT:

CONCLUSION:

Thus, We have successfully Evaluated Postfix Expression using Stack ADT.

You might also like