Skip to main content

Evaluating Postfix Expression

 Evaluating Postfix Expression



CODE

👇

  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #define MAX 20
  4. typedef struct
  5. {
  6. int data[MAX];
  7. int top;
  8. }STACK;

  9. void initstack(STACK *ps)
  10. {
  11. ps->top = -1;
  12. }

  13. void push(STACK *ps, int num)
  14. {
  15. ps->top++;
  16. ps->data[ps->top]=num;
  17. }

  18. int pop(STACK *ps)
  19. {
  20. return(ps->data[ps->top--]);
  21. }

  22. int isempty(STACK *ps)
  23. {
  24. return(ps->top == -1);
  25. }

  26. int isfull(STACK *ps)
  27. {
  28. return(ps->top == MAX-1);
  29. }

  30. void main()
  31. {
  32. void Eval(char post[]);
  33. char post[20];
  34. printf(">>Evaluating Postfix Expression<<\n");
  35. printf("Enter The Postfix Expression:\t");
  36. scanf("%s", post);
  37. Eval(post);
  38. }

  39. void Eval(char post[])
  40. {
  41. int value, i, op1, op2;
  42. STACK s1;
  43. initstack(&s1);
  44. for(i=0; post[i]!='\0'; i++)
  45. {
  46. if(isalpha(post[i]))
  47. {
  48. printf("Enter The Value Of %c: \t", post[i]);
  49. scanf("%d", &value);
  50. push(&s1, value);
  51. }
  52. else
  53. {
  54. op2=pop(&s1);
  55. op1=pop(&s1);
  56. switch(post[i])
  57. {
  58. case '+':
  59. push(&s1, op1+op2);
  60. break;
  61. case '-':
  62. push(&s1, op1-op2);
  63. break;
  64. case '*':
  65. push(&s1, op1*op2);
  66. break;
  67. case '/':
  68. push(&s1, op1/op2);
  69. break;
  70. case '%':
  71. push(&s1, op1%op2);
  72. break;
  73. default:
  74. printf("Enter Value The Value Of");
  75. scanf("%d", &value);
  76. push(&s1, value);
  77. break;
  78. }
  79. }
  80. }
  81. printf("The Result Is: %d \n", pop(&s1));
  82. }


👉Execute👈

//OUTPUT

/*

>>Evaluating Postfix Expression<<

Enter The Postfix Expression:   ABC*+DE/-

Enter The Value Of A:   78

Enter The Value Of B:   14

Enter The Value Of C:   64

Enter The Value Of D:   52

Enter The Value Of E:   43

The Result Is: 973

*/




                                        //ThE ProFessoR

Comments