Advertisement
Sathvikks8

Solve_Postfix_Expression.c

Sep 27th, 2020
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<ctype.h>
  4. #include<math.h>
  5. #define MAX 20
  6. float STACK[MAX];
  7. int top=-1;
  8. char postfix[100];
  9. int isEmpty()
  10. {
  11.   if(top==-1)
  12.     return 1;
  13.   else
  14.     return 0;
  15. }
  16. int isFull()
  17. {
  18.   if(top==MAX-1)
  19.     return 1;
  20.   else
  21.     return 0;
  22. }
  23. void PUSH(float ch)
  24. {
  25.   if(isFull())
  26.   {
  27.     printf("\nStack Overflow");
  28.     exit(0);
  29.   }
  30.   else
  31.     STACK[++top]=ch;
  32. }
  33. float POP()
  34. {
  35.   if(isEmpty())
  36.   {
  37.     printf("\nStack Underflow");
  38.     exit(0);
  39.   }
  40.   else
  41.     return(STACK[top--]);
  42. }
  43. void solvePostfix()
  44. {
  45.   int i=0;
  46.   float operand1, operand2;
  47.   for(;postfix[i]!='\0';i++)
  48.   {
  49.     char ch=postfix[i];
  50.     if(ch==' ')
  51.       continue;
  52.     if(isdigit(ch) && !isFull())
  53.     {
  54.       PUSH(ch-'0');
  55.       continue;
  56.     }
  57.     else
  58.     {
  59.       if(!isEmpty())
  60.       {
  61.         operand2=POP();
  62.         if(isEmpty())
  63.         {
  64.           printf("\nInsuffienct Operands entered.");
  65.           exit(0);
  66.         }
  67.         operand1=POP();
  68.         switch(ch)
  69.         {
  70.           case '+':
  71.             PUSH(operand1+operand2);
  72.           break;
  73.           case '-':
  74.             PUSH(operand1-operand2);
  75.           break;
  76.           case '*':
  77.             PUSH(operand1*operand2);
  78.           break;
  79.           case '/':
  80.             PUSH(operand1/operand2);
  81.           break;
  82.           case '^':
  83.             PUSH(pow(operand1,operand2));
  84.           break;
  85.           case '%':
  86.             PUSH(remainder(operand1,operand2));
  87.           break;
  88.           default:
  89.           {
  90.             printf("\nUnkown operator recieved");
  91.             exit(0);
  92.           }
  93.         }
  94.       }
  95.       else
  96.       {
  97.         printf("\nStack Underflow");
  98.         exit(0);
  99.       }
  100.     }
  101.   }
  102.   if(!isEmpty())
  103.     printf("\nThe result after solving the entered postfix expression is: %.2f", POP());
  104. }
  105. int main()
  106. {
  107.   printf("\nEnter a postfix expression to solve: ");
  108.   gets(postfix);
  109.   solvePostfix();
  110. }
  111.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement