Search more programs

C program for Evaluating a Prefix Expression

".C" file is available in downloadable format at :


(Open the link and click on the download arrow on the top right to download the file.)


Given below is the code for "C program for Evaluating a Prefix Expression" :

-----------------------------------------------------------------------------------


#include<stdio.h>
#include<string.h>

#define size 20

void streverse(char*);
int push(int x);
int pop();
int evalprefix();
int eval(int,int,char);


struct stack
{
int b[size];
int top;
}s;

int main()
{
s.top=-1;
int y;
char ch;
y=evalprefix();
printf("Evalution of prefix expression is %d",y);
return 0;

}



int evalprefix()

{
char a[size];
char *x;
printf("Enter prefix expression:\t");
    scanf("%s",a);
   streverse(a);
int i=0,op1,op2,r,y;
char ch;
while((ch=a[i])!='\0')
{
if((ch>='0')&&(ch<='9'))
push(ch-'0');

else{
op1=pop();
op2=pop();
r=eval(op1,op2,ch);
push(r);
}
i++;
}
y=pop();
return y;
}


int eval(int a,int b,char c)
{

     switch(c)
{
case '+':return(a+b);
case '-':return(a-b);
case '*':return(a*b);
case '/':return(a/b);

}
}

int push(int x)
{
s.top++;
s.b[s.top]=x;
return(s.b[s.top]);
}


int pop()
{
return(s.b[s.top--]); 
}


void streverse(char* str) { 
    int len = strlen(str);
    char a[len]; 
    int i;
    for ( i = 0; i < len; i++) { 
        a[i] = str[len - 1 - i]; 
    }; 

    for ( i = 0; i < len; i++) { 
        str[i] = a[i]; 
    }

}

-----------------------------------------------------------------------------------

No comments:

Post a Comment