Search Tutorials

Loading...

Saturday, 20 April 2013

C code to eveluate Postfix Expression

/*C program to evaluate the given postfix expression*/

# include<stdio.h> 
# include<conio.h> 

typedef struct 

int a[100]; 
int top; 
}STACK; 
void push(STACK *s,int x) 

if(s->top==99) 
printf("STACK OVERFLOW\n"); 
else 
s->a[++s->top]=x; 


int pop(STACK *s) 

int x; 
if(s->top<0) 
printf("STACK UNDERFLOW\n"); 
else 

x=s->a[s->top--]; 
return x; 


int operation(int p1,int p2,char op) 

switch(op) 

case '+':return p1+p2; 
case '*':return p1*p2; 
case '-':return p1-p2; 
case '/':return p1/p2; 


int evaluate(char pos[]) 

STACK s1; 
int p1,p2,result,i; 
s1.top=-1; 
for(i=0;pos[i]!='\0';i++) 
if(isdigit(pos[i])) 
push(&s1,pos[i]-'0');/*use to find the integer value of it*/ 
else 

p2=pop(&s1); 
p1=pop(&s1); 
result=operation(p1,p2,pos[i]); 
push(&s1,result); 
}/*end of for loop*/ 
return pop(&s1); 

int main() 

char postfix[100]; 
//clrscr(); 
printf("Please Enter the VALID POSTFIX string\n\n Operands are SINGLE DIGIT\n\n"); 
gets(postfix); 
printf("The Result is==>%d",evaluate(postfix)); 
getch(); 
}/*end of main*/

/* Output of Postfix Expression Evaluation Program */

C code to eveluate Postfix Expression
Output of Postfix Expression Program

For more related to Data Structure see List of Data Structure Programs. If you like this program, Please share and comment to improve this blog.

No comments:

Post a Comment

Back to Top