Skip to content

Instantly share code, notes, and snippets.

@priyadarshitathagat
Created October 3, 2016 18:11
Show Gist options
  • Save priyadarshitathagat/6db1e3618ebf6401fb0f7e216930e148 to your computer and use it in GitHub Desktop.
Save priyadarshitathagat/6db1e3618ebf6401fb0f7e216930e148 to your computer and use it in GitHub Desktop.
Evaluation of a given prefix expression containing single digits number as operands
#include<stdio.h>
#include<string.h>
int top=-1; char a[20];
void push(char x)
{
a[++top]=x;
}
char pop()
{
return(a[top--]);
}
int evaluate(char s[])
{
int i=0,j=0; char ch,c,b; int sum=0,x=0;
while(s[i]!='\0')
{ ch=s[i];
if((ch=='+')||(ch=='-')||(ch=='/')||(ch=='*'))
{
push(ch);
}
else
{ x=ch-'0';
while((top!=-1)&&(a[top]=='@'))
{
c=pop(); b=pop();
if(b=='+')
sum+=x;
else if(b=='-')
sum-=x;
else if(b=='/')
sum/=x;
else if(b=='*')
sum*=x;
x=sum;
}
sum=x; push('@');
}
i++;
}
return(sum);
}
main()
{ char s[20]; printf("Enter a prefix expression: ");
gets(s);
int sum=evaluate(s);
printf("Answer : %d",sum);
}
/////////////////////
//OUTPUT
//Enter a prefix expression: */123
//Answer : 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment