C Program for Postfix Evaluation using Stack:
#include<stdio.h>
#include<string.h>
int stk[20];
void push(char);
char pop();
int top=-1;
int main()
{
char post[20];
int a,b,i;
printf("\n Enter the postfix expression:");
gets(post);
for(i=0;i<strlen(post);i++)
{
if(post[i]=='+'||post[i]=='-'||post[i]=='*')
{
a=pop();
b=pop();
if(post[i]=='+')
push(b+a);
if(post[i]=='-')
push(b-a);
if(post[i]=='*')
push(b*a);
}
else
push(post[i]-'0');
}
printf("\n The output is:");
printf("%d",stk[top]);
return 0;
}
void push(char m)
{
top++;
stk[top]=m;
}
char pop()
{
return(stk[top--]);
}
#include<stdio.h>
#include<string.h>
int stk[20];
void push(char);
char pop();
int top=-1;
int main()
{
char post[20];
int a,b,i;
printf("\n Enter the postfix expression:");
gets(post);
for(i=0;i<strlen(post);i++)
{
if(post[i]=='+'||post[i]=='-'||post[i]=='*')
{
a=pop();
b=pop();
if(post[i]=='+')
push(b+a);
if(post[i]=='-')
push(b-a);
if(post[i]=='*')
push(b*a);
}
else
push(post[i]-'0');
}
printf("\n The output is:");
printf("%d",stk[top]);
return 0;
}
void push(char m)
{
top++;
stk[top]=m;
}
char pop()
{
return(stk[top--]);
}
OUTPUT |
No comments:
Post a Comment