Hello friends!!!!!
Postfix evaluation
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 100
struct stack {
int arr[MAX];
int top;
};
typedef struct stack Stack;
// Function to initialize the stack
void initialisation(Stack* s) {
s->top = -1;
}
// Function that check whether the stack is full or not
int isFull(Stack* s) {
return s->top == MAX - 1;
}
// Function to check if the stack is empty
int isEmpty(Stack* s) {
return s->top == -1;
}
// push operation
void push(Stack* s, int value) {
if (isFull(s)) {
printf("Stack overflow!\n");
} else {
s->arr[++s->top] = value;
}
}
// pop function
int pop(Stack* s) {
if (isEmpty(s)) {
printf("Stack underflow!\n");
return -1;
} else {
int popped_Value = s->arr[s->top--];
return popped_Value;
}
}
int evaluation_of_postfix(char *expr)
{
int i, op1, op2;
Stack s;
initialisation(&s);
for(i=0; expr[i] != '\0'; i++)
{
if(isdigit(expr[i]))
{
push(&s, expr[i] - '0');
}
else if(expr[i] == '+' || expr[i] == '-' || expr[i] == '*' || expr[i] == '/')
{
op2 = pop(&s);
op1 = pop(&s);
switch(expr[i])
{
case '+':
push(&s, op1 + op2);
break;
case '-':
push(&s, op1 - op2);
break;
case '*':
push(&s, op1 * op2);
break;
case '/':
push(&s, op1 / op2);
break;
}
}
}
return pop(&s);
}
void main()
{
char postfix[MAX];
printf("Enter a postfix expression: ");
scanf("%s", postfix);
int result = evaluation_of_postfix(postfix);
printf("The result of the postfix expression is: %d\n", result);
}