Evaluation of Postfix expression using Stack in C program.
CODING:
#include<stdio.h>
#include<conio.h>
#define max 50
float st[max];
int top=-1;
void push(float st[],float num);
float pop(float st[]);
float postex(char exp[]);
void main()
{
float num;
char exp[50];
clrscr();
printf("ENTER THE POSTFIX EXPRESSION:\n");
fflush(stdin);
gets(exp);
num=postex(exp);
printf("\nANSWER OF THE POSTFIX EXPRESSION:%f",num);
getch();
}
float postex(char exp[])
{
int i=0;
float no1,no2,num;
while(exp[i]!='\0')
{
if(isdigit(exp[i]))
push(st,(float)(exp[i]-'0'));
else
{
no1=pop(st);
no2=pop(st);
switch(exp[i])
{
case '+':
num=no1+no2;
break;
case '-':
num=no1-no2;
break;
case '*':
num=no1*no2;
break;
case '/':
num=no1/no2;
break;
case '%':
num=(int)no1%(int)no2;
break;
}
push(st,num);
}
i++;
}
return (pop(st));
}
void push(float st[],float num)
{
if(top==max-1)
printf("\nSTACK IS OVERFLOW...");
else
{
top++;
st[top]=num;
}
}
float pop(float st[])
{
float num;
if(top==-1)
printf("\nSTACK IS UNDERFLOW...");
else
{
num=st[top];
top--;
}
return num;
}
CODING:
#include<stdio.h>
#include<conio.h>
#define max 50
float st[max];
int top=-1;
void push(float st[],float num);
float pop(float st[]);
float postex(char exp[]);
void main()
{
float num;
char exp[50];
clrscr();
printf("ENTER THE POSTFIX EXPRESSION:\n");
fflush(stdin);
gets(exp);
num=postex(exp);
printf("\nANSWER OF THE POSTFIX EXPRESSION:%f",num);
getch();
}
float postex(char exp[])
{
int i=0;
float no1,no2,num;
while(exp[i]!='\0')
{
if(isdigit(exp[i]))
push(st,(float)(exp[i]-'0'));
else
{
no1=pop(st);
no2=pop(st);
switch(exp[i])
{
case '+':
num=no1+no2;
break;
case '-':
num=no1-no2;
break;
case '*':
num=no1*no2;
break;
case '/':
num=no1/no2;
break;
case '%':
num=(int)no1%(int)no2;
break;
}
push(st,num);
}
i++;
}
return (pop(st));
}
void push(float st[],float num)
{
if(top==max-1)
printf("\nSTACK IS OVERFLOW...");
else
{
top++;
st[top]=num;
}
}
float pop(float st[])
{
float num;
if(top==-1)
printf("\nSTACK IS UNDERFLOW...");
else
{
num=st[top];
top--;
}
return num;
}
Comments
Post a Comment