Friday, 4 November 2016

Program 9 - Evaluation of Postfix Expression



#include <stdio.h>
int stack[100];
int top = -1;
//(a+b)*(c+d)
//ab+cd+*
int evaluate(char postfix[]){
int i, op1, op2, temp;
char ch;
for(i = 0; postfix[i] != '\0'; i++){
ch = postfix[i];
if(isdigit(ch)){
stack[++top] = ch - '0';
} else if(isalpha(ch)){
printf("Enter value of %c: ", ch);
scanf("%d", &temp);
stack[++top] = temp;
} else if(ch == '+' || ch == '-' || ch == '*' || ch =='/'){
op2 = stack[top--];
op1 = stack[top--];
switch(ch){
case '+':
stack[++top] = op1 + op2;
break;
case '-':
stack[++top] = op1 - op2;
break;
case '*':
stack[++top] = op1 * op2;
break;
case '/':
stack[++top] = op1 / op2;
break;
}
}
}
return stack[top--];
}
int main(){
char postfix[20];
printf("Enter postfix expression: ");
gets(postfix);
printf("The evalutaion of the given expression is: \n%d",evaluate(postfix));
}


























































































No comments:

Post a Comment