Evaluation of Postfix Expression in C [Algorithm and Program]

Here you will get calculation and program for the development of postfix articulation in C.

In postfix or turn around clean documentation, each administrator pursues the entirety of its operands.

For instance: 5 3 2 * +

The calculation for Evaluation of Postfix Expression

Make a vacant stack and start filtering the postfix articulation from left to right.

On the off chance that the component is an operand, push it into the stack.

In the event that the component is an administrator O, pop twice and get An and B individually.

Figure BOA and drive it back to the stack.

At the point when the articulation is finished, the incentive in the stack is the last answer.

Assessment of a postfix articulation utilizing a stack is clarified in underneath example:

Program

//Assumption -- primary operators '-,+,*,/,%' operand -- a single digit
 
#include<stdio.h>
 
#define MAX 20
 
typedef struct stack
{
	int data[MAX];
	int top;
}stack;
 
void init(stack *);
int empty(stack *);
int full(stack *);
int pop(stack *);
void push(stack *,int);
int evaluate(char x,int op1,int op2);
 
int main()
{
	stack s;
	char x;
	int op1,op2,val;
	init(&s);
	printf("Enter the expression(eg: 59+3*)\nSingle digit operand and operators only:");
	
	while((x=getchar())!='\n')
	{
		if(isdigit(x))
			push(&s,x-48);		//x-48 for removing the effect of ASCII
		else
		{
			op2=pop(&s);
			op1=pop(&s);
			val=evaluate(x,op1,op2);
			push(&s,val);
		}
	}
	
	val=pop(&s);
	printf("\nValue of expression=%d",val);
 
	return 0;
}
 
int evaluate(char x,int op1,int op2)
{
	if(x=='+')
		return(op1+op2);
	if(x=='-')
		return(op1-op2);
	if(x=='*')
		return(op1*op2);
	if(x=='/')
		return(op1/op2);
	if(x=='%')
		return(op1%op2);
}
 
void init(stack *s)
{
	s->top=-1;
}
 
int empty(stack *s)
{
	if(s->top==-1)
		return(1);
	
	return(0);
}
 
int full(stack *s)
{
	if(s->top==MAX-1)
		return(1);
	
	return(0);
}
 
void push(stack *s,int x)
{
	s->top=s->top+1;
	s->data[s->top]=x;
}
 
int pop(stack *s)
{
	int x;
	x=s->data[s->top];
	s->top=s->top-1;
	
	return(x);
}

Output

Enter the expression(eg: 59+3*)
Single digit operand and operators only:74+5-

Value of expression=6

Leave a Comment

error: Alert: Content is protected!!