program to evaluate postfix expression in c code example

Example 1: Postfix evaluation in c

//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);
}

Example 2: C Program to evaluate postfix expression using stack

#include<stdio.h>
int stack[20];
int top = -1;

void push(int x)
{
    stack[++top] = x;
}

int pop()
{
    return stack[top--];
}

int main()
{
    char exp[20];
    char *e;
    int n1,n2,n3,num;
    printf("Enter the expression :: ");
    scanf("%s",exp);
    e = exp;
    while(*e != '\0')
    {
        if(isdigit(*e))
        {
            num = *e - 48;
            push(num);
        }
        else
        {
            n1 = pop();
            n2 = pop();
            switch(*e)
            {
            case '+':
            {
                n3 = n1 + n2;
                break;
            }
            case '-':
            {
                n3 = n2 - n1;
                break;
            }
            case '*':
            {
                n3 = n1 * n2;
                break;
            }
            case '/':
            {
                n3 = n2 / n1;
                break;
            }
            }
            push(n3);
        }
        e++;
    }
    printf("\nThe result of expression %s  =  %d\n\n",exp,pop());
    return 0;
}

Tags:

Misc Example