Advertisement
Guest User

reverse polish notation (invalid)

a guest
Jan 23rd, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "stack.h"
  4.  
  5.  
  6. void getInput()
  7. {
  8.     char ch;
  9.  
  10.     while(1)
  11.     {
  12.         makeEmpty();
  13.  
  14.         printf("Enter an RPN expression: ");
  15.  
  16.         scanf("%c", &ch);
  17.  
  18.         if(ch == 'q')
  19.                 break;
  20.  
  21.         while(1)
  22.         {
  23.             if(ch == '\n')
  24.                 break;
  25.  
  26.             if(ch >= 48 && ch <= 57)
  27.             {
  28.                 if(!isFull())
  29.                 {
  30.                     push(ch - 48);
  31.                 }
  32.                 else
  33.                 {
  34.                     printf("Expression is too complex\n");
  35.                     exit(EXIT_FAILURE);
  36.                 }
  37.  
  38.             }
  39.  
  40.             switch(ch)
  41.             {
  42.                 case '+':
  43.                     push(add(pop(), pop()));
  44.                     break;
  45.                 case '-':
  46.                     push(sub(pop(), pop()));
  47.                     break;
  48.                 case '*':
  49.                     push(mul(pop(), pop()));
  50.                     break;
  51.                 case '/':
  52.                     push(divide(pop(), pop()));
  53.                     break;
  54.                 case '=':
  55.                     printf("%d\n", pop());
  56.                     break;
  57.             }
  58.  
  59.             scanf("%c", &ch);
  60.         }
  61.     }
  62. }
  63.  
  64. int add(int a, int b)
  65. {
  66.     return a + b;
  67. }
  68.  
  69. int sub(int a, int b)
  70. {
  71.     return a - b;
  72. }
  73.  
  74. int mul(int a, int b)
  75. {
  76.     return a * b;
  77. }
  78.  
  79. int divide(int a, int b)
  80. {
  81.     return a / b;
  82. }
  83.  
  84. int main()
  85. {
  86.  
  87.     getInput();
  88.     printf("%d\n", pop());
  89.  
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement