Created
October 3, 2016 18:11
-
-
Save priyadarshitathagat/d1f5b0c426dcab6fa3622be36be60be5 to your computer and use it in GitHub Desktop.
Evaluation of a given postfix 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--]); | |
} | |
StrRev(char *s) | |
{ int i=0; char c; int j=strlen(s); j--; | |
while(i<=j) | |
{ | |
c=*(s+i); | |
*(s+i)=*(s+j); | |
*(s+j)=c; | |
i++; j--; | |
} | |
} | |
float evaluate(char s[]) | |
{ | |
int i=0; char ch,c,b; int sum=0,x=0; StrRev(s); | |
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/sum; | |
else if(b=='*') | |
sum*=x; | |
x=sum; | |
} | |
sum=x; push('@'); | |
} | |
i++; | |
} | |
return(sum); | |
} | |
main() | |
{ char s[20]; printf("Enter a postfix expression : "); | |
gets(s); | |
int sum=evaluate(s); | |
printf("Answer : %d",sum); | |
} | |
///////////// | |
//OUTPUT | |
//Enter a postfix expression : 123*+ | |
//Answer : 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment