tampurus

2.4 Evaluation of Postfix expression

Nov 25th, 2021 (edited)
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. /*
  2. Input  :
  3.        Enter the postfix expression 84+
  4.  
  5. Output :
  6.        The final answer is 12
  7.  
  8. Assumptions
  9. -> Evaluation of only +,-,* and / will take place.
  10. -> Input expression must be single digit operands.
  11. */
  12. #include<stdio.h>
  13. #include<conio.h>
  14. #define Stack_Size 50
  15. int stack[Stack_Size],top=-1;
  16. void Push(int element){
  17.     if(top == Stack_Size-1){
  18.         printf("\nStack is full");
  19.     }
  20.     else
  21.         stack[++top]=element;
  22. }
  23. int Pop(){
  24.     int Poped_value = stack[top];
  25.     stack[top--]=0;
  26.     return Poped_value;
  27. }
  28. void Solve(char operator){
  29.     int b = Pop();
  30.     if(operator == '+'){
  31.         Push(Pop() + b);
  32.     }
  33.     else if(operator == '-'){
  34.         Push(Pop() - b);
  35.     }
  36.     else if(operator == '*'){
  37.         Push(Pop() * b);
  38.     }
  39.     else{
  40.         Push(Pop() / b);
  41.     }
  42. }
  43. int Evaluation(char exp[]){
  44.     for(int i=0 ; exp[i] != '\0' ; i++){
  45.         if(exp[i]>='0' && exp[i]<='9'){
  46.             Push(exp[i]-'0');
  47.         }
  48.         else{
  49.             Solve(exp[i]);
  50.         }
  51.     }
  52.     return stack[top];
  53. }
  54. int main()
  55. {
  56.     char exp[20];
  57.     printf("Enter the postfix expression ");
  58.     scanf("%s",exp);
  59.     printf("\nThe final answer is %d",Evaluation(exp));
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment