C source code for postfix evaluation

, by Engineer's Vision


/* postfix evaluation */

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 50
typedef struct stack
{
int data[MAX];
int top;
}stack;
void init(stack*);
void push(stack*,int);
void evaluate(char postfix[]);
int pop(stack*);
void main()
{
char postfix[30];
clrscr();
printf("enter the postfix expression");
gets(postfix);
evaluate(postfix);
getch();
}

void init(stack *s)
{
s->top= -1;
}
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);
}
void evaluate(char postfix[])
{
stack s;
int op1,op2,val=0,i;
init(&s);
for(i=0;postfix[i]!='\0';i++)
 {
 if(isalpha(postfix[i]))
  {
  printf("\n enter the value of %c",postfix[i]);
  scanf("%d",&val);
  push(&s,val);
  }
 else
  {
  op2=pop(&s);
  op1=pop(&s);
  switch(postfix[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;
   case '%': push(&s,op1%op2); break;
   }
  }
 }
 val=pop(&s);
 printf("\n value of the expression is %d",val);
 getch();
}

0 comments: