Stack Program #6

20. Write a program for evaluation of pre-fix expression using Stack.




#include<stdio.h>
#include<string.h>
#define N 50
char s[N];
int top=-1;
void push(int);
int pop();
int perform(int oprand1,int oprand2,char temp);
void main()
{
     int i=0,value=0,oprand1,oprand2,x,result,l=0;
     char prefix[50],temp;
     printf("Enter the prefix expression:\n");
     scanf("%s",prefix);
     l=strlen(prefix);
     i=l-1;
     temp=prefix[i];
     while(i>=0)
     {
     if(temp>='0' && temp<='9')
     {
          push(temp-'0');
     }
     else
     {
          oprand1=pop();
          oprand2=pop();
          value=perform(oprand1,oprand2,temp);
          push(value);
     }
     i--;
     temp=prefix[i];
     }
     result=pop();
     printf("Evaluation of prefix exp. is %d\n",result);
}
void push(int x)
{
     if(top>=N-1)
     {
         
          printf("STACK OVERFLOW\n");
     }
     else
     {
          top++;
          s[top]=x;
     }
}
int pop()
{
     if(top==-1)
     {
          printf("STACK UNDERFLOW\n");
          return('\0');
     }
     else
     {
          top=top-1;
          return(s[top+1]);
     }
}
int perform(int oprand1,int oprand2,char temp)
{
     int j=1,ans;
     if(temp=='+')
     {
          return(oprand1+oprand2);
     }
     else if(temp=='-')
     {
          return(oprand1-oprand2);
     }
      else if(temp=='*')
     {
          return(oprand1*oprand2);
     }
      else if(temp=='/')
     {
          return(oprand1/oprand2);
     }
      else if(temp=='^' || temp=='$')
     {
          for(j=1;j<=oprand2;j++)
          {
               ans=oprand1*ans;
          }
          return(ans);
     }
}

Output

  1. Enter the prefix expression:
    +*48-6+6*84
    Evaluation of prefix exp. is 0
  2. Enter the prefix expression:
    -*+4325
    Evaluation of prefix exp. is 9
     


For download this program please check the link ➡➡ Download

Comments

Popular

Basic Program #3

Pointer Program #1

Array Program #4

Singly Linked List program #1

Basic program #2