/************************************************************
* Filename: postfix_evaluation.c
* Description: postfix evaluation using stack
* Author:Sarju S
* Date: 02-Dec-2011
*************************************************************/
#include
#include
#define MAX_EXPR_SIZE 100
#define MAX_STACK_SIZE 100
typedef enum {eos,lparen, rparen, plus, minus, times, divide,mod,operand} precedence;
char postfixExpr[MAX_EXPR_SIZE];
int stack[MAX_STACK_SIZE];
int top=-1,postfixCount=0;
void stackFull()
{
fprintf(stderr, "Stack is full cannot add elements\n");
exit(EXIT_FAILURE);
}
void stackEmpty()
{
fprintf(stderr, "Stack is empty cannot delete elements\n");
exit(EXIT_FAILURE);
}
void push(int item)
{/* add an element to stack */
if(top>=MAX_STACK_SIZE-1)
stackFull();
top++;
stack[top] = item;
}
int pop()
{/*Delete top element from the stack*/
if(top==-1)
stackEmpty();
return stack[top--];
}
precedence getToken(char *symbol)
{ /* get the next token, symbol is the character representation,which is
returned, the token is represented by its enumerated value, which is
returned in the function name */
*symbol = postfixExpr[postfixCount];
postfixCount++;
switch(*symbol) {
case '\0': return eos;
case '(' : return lparen;
case ')' : return rparen;
case '+' : return plus;
case '-' : return minus;
case '/' : return divide;
case '*' : return times;
case '%' : return mod;
default : return operand;
}
}
int postfixEvaluate(){
/* evaluate a postfix expression and returns the result */
precedence token;
char symbol;
int op1,op2;
token = getToken(&symbol);
while(token!=eos){
if(token==operand)
push(symbol-'0');
else{
/* pop two operands, perform operation and
push result to stack */
op2 = pop();
op1 = pop();
switch(token){
case plus :push(op1+op2);
break;
case minus :push(op1-op2);
break;
case times :push(op1*op2);
break;
case divide :push(op1/op2);
break;
case mod :push(op1%op2);
}
}
token = getToken(&symbol);
}
return pop();/* return result */
}
void main(){
int result;
printf("\nEnter the POSTFIX expression:");
scanf("%s",postfixExpr);
result=postfixEvaluate(); /* Function Call*/
printf("\nThe Result is:%d",result);
}
OUTPUT
krishnakripa@krishnakripa-K8Upgrade-VM800:~$ gcc postfix_evaluation.c
krishnakripa@krishnakripa-K8Upgrade-VM800:~$ ./a.out
Enter the POSTFIX expression:62/3-42*+
The Result is:8
krishnakripa@krishnakripa-K8Upgrade-VM800:~$
0 comments:
Post a Comment