Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<ctype.h>
- #include<math.h>
- #define MAX 20
- float STACK[MAX];
- int top=-1;
- char postfix[100];
- int isEmpty()
- {
- if(top==-1)
- return 1;
- else
- return 0;
- }
- int isFull()
- {
- if(top==MAX-1)
- return 1;
- else
- return 0;
- }
- void PUSH(float ch)
- {
- if(isFull())
- {
- printf("\nStack Overflow");
- exit(0);
- }
- else
- STACK[++top]=ch;
- }
- float POP()
- {
- if(isEmpty())
- {
- printf("\nStack Underflow");
- exit(0);
- }
- else
- return(STACK[top--]);
- }
- void solvePostfix()
- {
- int i=0;
- float operand1, operand2;
- for(;postfix[i]!='\0';i++)
- {
- char ch=postfix[i];
- if(ch==' ')
- continue;
- if(isdigit(ch) && !isFull())
- {
- PUSH(ch-'0');
- continue;
- }
- else
- {
- if(!isEmpty())
- {
- operand2=POP();
- if(isEmpty())
- {
- printf("\nInsuffienct Operands entered.");
- exit(0);
- }
- operand1=POP();
- switch(ch)
- {
- case '+':
- PUSH(operand1+operand2);
- break;
- case '-':
- PUSH(operand1-operand2);
- break;
- case '*':
- PUSH(operand1*operand2);
- break;
- case '/':
- PUSH(operand1/operand2);
- break;
- case '^':
- PUSH(pow(operand1,operand2));
- break;
- case '%':
- PUSH(remainder(operand1,operand2));
- break;
- default:
- {
- printf("\nUnkown operator recieved");
- exit(0);
- }
- }
- }
- else
- {
- printf("\nStack Underflow");
- exit(0);
- }
- }
- }
- if(!isEmpty())
- printf("\nThe result after solving the entered postfix expression is: %.2f", POP());
- }
- int main()
- {
- printf("\nEnter a postfix expression to solve: ");
- gets(postfix);
- solvePostfix();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement