Created
October 3, 2016 18:11
-
-
Save priyadarshitathagat/6db1e3618ebf6401fb0f7e216930e148 to your computer and use it in GitHub Desktop.
Evaluation of a given prefix expression containing single digits number as operands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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