Tuesday 31 January 2017

Evaluating Postfix expression using stack : C program

#include<stdio.h>
#define MAX 50
int stack[MAX];
int top=-1;
void push(int item)
{
if(top == MAX-1)
{
printf("stack is full");
return;
}
top=top+1;
stack[top]=item;
}

int pop()
{
if(top == -1)
{
printf("stack empty");
return;
}
int temp;
temp=stack[top];
top=top-1;
return temp;
}
main()
{
char ch;
int val,v3,v2,v1,i;
printf("enter the postfix expression\n At the end type #");
fflush(stdin);
scanf("%c",&ch);
while(ch != '#')
{
if(ch=='a' || ch == 'b'|| ch == 'c')
{
printf("enter the value of %c",ch);
scanf("%d",&val);
push(val);
}

if(ch == '+'||ch == '-'||ch == '*'||ch == '/')
{
v1=pop();
v2=pop();
switch(ch)
{
case '+': v3=v2+v1;
break;
case '-': v3=v2-v1;
break;
case '*': v3=v2*v1;
break;
case '/': v3=v2/v1;
break;
}
push(v3);
}
fflush(stdin);
scanf("%c",&ch);
}
val=pop();
printf("\nresultant is %d",val);
}





No comments:

Post a Comment