Advertisement
Arnab_Manna

PrefixEval

Dec 16th, 2022
593
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<ctype.h>
  4. #include<string.h>
  5. #define MAX 100
  6.  
  7. int stack[MAX];
  8. int top = -1;
  9.  
  10. void push(int x)
  11. {
  12.     stack[++top]= x;
  13. }
  14.  
  15. int pop()
  16. {
  17.     if(top == -1)
  18.         return -1;
  19.     else
  20.     {
  21.         return stack[top--];    
  22.     }  
  23. }
  24.  
  25. int POW(int n,int m)
  26. {
  27.     int i,res=1;
  28.     for(i=1;i<=m;i++)
  29.     {
  30.         res=res*n;
  31.     }
  32.     return res;
  33. }
  34.  
  35. int main()
  36. {
  37.     char exp[MAX],*ptr;
  38.     char data;
  39.     int i,k,op1,op2,res=0;
  40.    
  41.     printf("\n Enter Exp. =");
  42.     scanf("%s",exp);
  43.     ptr=strrev(exp);
  44.     for(i=0;ptr[i]!='\0';i++)
  45.     {
  46.         data=ptr[i];
  47.         if(isalpha(exp[i]))
  48.         {
  49.             printf("kaka  %c er velu dao :",data);
  50.             scanf("%d",&k);
  51.             push(k);
  52.         }
  53.         else
  54.         {
  55.             op1=pop();
  56.             op2=pop();
  57.             switch(data)
  58.             {
  59.                 case '+':
  60.                     res=op1+op2;
  61.                     break;
  62.                 case '-':
  63.                     res=op1-op2;
  64.                     break;
  65.                 case '*':
  66.                     res=op1*op2;
  67.                     break;
  68.                 case '/':
  69.                     res=op1/op2;
  70.                     break;
  71.                 case '%':
  72.                     res=op1%op2;
  73.                     break;
  74.                 case '^':
  75.                     res=POW(op1,op2);
  76.                     break;
  77.             }
  78.             push(res);  
  79.         }
  80.     }
  81.     printf("%d",stack[0]);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement