C Program to implement Postfix expression evaluation for multiple digits number - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

C Program to implement Postfix expression evaluation for multiple digits number

Share This
C Program to implement Postfix expression evaluation for multiple digits number
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define SIZE 50 int top=-1; push(int *stack,int item) { stack[++top]=item; } int pop(int *stack) { return(stack[top--]); } int main() { char *pofx,ch; int i=0,op1,op2,*stack; pofx=(char *)malloc(sizeof(char)*SIZE); stack=(int *)malloc(sizeof(int)*SIZE); printf("\n....Please!! enter ; after every operand and operator.......\n"); /*here ; is used for delimeter*/ printf("enter the postfix expression:"); scanf("%s",pofx); //scan the symbols from left to right one after another while(i<strlen(pofx)) { if(isdigit(pofx[i])) //If operand push to stack { int opr=0; while(pofx[i]!=';') { opr=(opr*10)+(pofx[i]-'0');/*pofx[i]-'0' is used for converting character to integer*/ i++; } /* if the symbol is operand then push into stack*/ push(stack,opr); } else if(pofx[i]==';') { i++; } else //If symbol is operator then pop top two elements from stack and push back the result into stack { ch=pofx[i]; op2=pop(stack); op1=pop(stack); switch(ch) { case '+': push(stack,(op1+op2)); break; case '-': push(stack,(op1-op2)); break; case '*': push(stack,(op1*op2)); break; case '/': push(stack,(op1/op2)); break; case '^': push(stack,(pow(op1,op2))); break; } i++; } } printf("\nresult after evaluation:%d\n",stack[top]); return 0; }



Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.