Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.29 KB | None | 0 0
  1. #include<stdio.h>     //standard input output functions
  2.        //console functions
  3. #include<string.h>       //string functions
  4. #define MAX 50              //max size defined
  5. int stack[MAX];             //a global stack
  6. char post[MAX];             //a global postfix stack
  7. int top=-1;                  //initializing top to -1
  8. void pushstack(int tmp);       //push function
  9. void evaluate(char c);          //calculate function
  10. void main()
  11. {
  12.    int i,l;
  13.    //clrscr();
  14.    printf("Insert a postfix notation :: ");
  15.    gets(post);                    //getting a postfix expression
  16.    l=strlen(post);               //string length
  17.    for(i=0;i<l;i++)
  18.    {
  19.       if(post[i]>='0' && post[i]<='9')
  20.       {
  21.           pushstack(i);             //if the element is a number push it
  22.       }
  23.       if(post[i]=='+' || post[i]=='-' || post[i]=='*' ||
  24.       post[i]=='/' || post[i]=='^')       //if element is an operator
  25.       {
  26.           evaluate(post[i]);             //pass it to the evaluate
  27.       }
  28.    }                      //print the result from the top
  29.    printf("\n\nResult :: %d",stack[top]);
  30.    
  31. }
  32.  
  33. void pushstack(int tmp)          //definiton for push
  34. {
  35.    top++;                              //incrementing top
  36.    stack[top]=(int)(post[tmp]-48);    //type casting the string to its integer value
  37. }
  38.  
  39. void evaluate(char c)       //evaluate function
  40. {
  41.    int a,b,ans;        //variables used
  42.    a=stack[top];       //a takes the value stored in the top
  43.    stack[top]='\0';     //make the stack top NULL as its a string
  44.    top--;                //decrement top's value
  45.    b=stack[top];         //put the value at new top to b
  46.    stack[top]='\0';      //make it NULL
  47.    top--;                //decrement top
  48.    switch(c)     //check operator been passed to evaluate
  49.    {
  50.       case '+':          //addition
  51.           ans=b+a;
  52.           break;
  53.       case '-':           //subtraction
  54.           ans=b-a;
  55.           break;
  56.       case '*':            //multiplication
  57.           ans=b*a;
  58.           break;
  59.       case '/':           //division
  60.           ans=b/a;
  61.           break;
  62.       case '^':      //power
  63.           ans=b^a;
  64.           break;
  65.       default:
  66.           ans=0;      //else 0
  67.    }
  68.    top++;             //increment top
  69.    stack[top]=ans;        //store the answer at top
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement