0% found this document useful (0 votes)
10 views4 pages

Postfix

Postfix evaluation and infix conversation
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

Postfix

Postfix evaluation and infix conversation
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

PROGRAM

#include<stdio.h>
#include<ctype.h>
char S[50],Q[50];
int top=-1,front=-1,rear=-1;
void ENQUEUE(char item)
{
if(rear==49)
printf("Queue is full");
else if(front==-1)
{
front=0;rear=0;
Q[rear]=item;
}
else
{
rear=rear+1;
Q[rear]=item;
}
}
void Display()
{
if(front==-1)
printf("Queue is empty");
else
for(int i=front;i<=rear;i++)
printf("%c ",Q[i]);

}
void PUSH(char item)
{
if(top!=49)
S[++top]=item;
}
char POP()
{
return S[top--];
}
int isOperator(char c)
{
return(c=='+'||c=='-'||c=='*'||c=='/'||c=='^');
}
int precedence(char c)
{
if(c=='+'||c=='-')
return 1;
if(c=='*'||c=='/')
return 2;
if(c=='^')
return 3;
}
void convert(char A[])
{
int i=0;
char ch;
while(A[i]!='\0')
{
ch=A[i];
if(isalnum(ch))
{
ENQUEUE(ch);
}
else if(ch=='(')
PUSH(ch);
else if(ch==')')
{
while(S[top]!='(')
ENQUEUE(POP());
POP();
}
else if(isOperator(ch))
{
if(S[top]=='('||top==-1)
PUSH(ch);
else
{
while(precedence(S[top])>=precedence(ch))
{
ENQUEUE(POP());
if(S[top]=='('||top==-1)
break;
}
PUSH(ch);
}
}
i++;
}
while(top!=-1)
ENQUEUE(POP());
}
void main()
{
char A[50];
printf("Enter Infix Expression\n");
scanf("%s",A);
convert(A);
Display();
}

OUTPUT
Enter Infix Expression
3-6*(7-1)
3 6 7 1 - * -
PROGRAM
#include<stdio.h>
#include<ctype.h>

int S[50],top=-1;

void PUSH(int item)


{
if(top!=49)
S[++top]=item;
}

int POP()
{
return S[top--];
}

int isOperator(char c)
{
return(c=='+'||c=='-'||c=='*'||c=='/');
}

int operate(int a, char c, int b)


{
switch(c)
{
case '+':
return (a+b);
break;
case '-':
return (a-b);
break;
case '*':
return (a*b);
break;
case '/':
return (a/b);
break;
}
}

int evaluate(char A[])


{
int i=0,op1,op2,in=0;
char ch;
while(A[i]!='\0')
{
ch=A[i];
if(isdigit(ch))
{
in=in*10+(A[i]-'0');
if (A[i+1]==' ')
{
PUSH(in);
in=0;
}

}
else if(isOperator(ch))
{
op2=POP();
op1=POP();
PUSH(operate(op1,ch,op2));
}
i++;
}
return POP();
}

void main()
{
char A[50];
printf("Enter Postfix Expression\n");
gets(A);
printf("%d",evaluate(A));

OUTPUT

Enter Postfix Expression


34 6 7 1 - * +
70

You might also like