Experiment No.5
Experiment No.5
Mandal’s,
Theory:
Infix and Postfix:
The computer understands binary operations which usually takes two operands. But our own expressions
can have multiple operands represented in postfix form.
We derive various solutions by solving these expressions. The compiler has a proper set of rules it follows
to compile these expressions and give a result.
Infix Expressions:
Postfix Expressions:
The postfix expression is of format; <operand><operand><operator> that is, the operator comes after the
operands.
Post fix expression is such that the operator succeeds the operands. This expression is readable by the
computer.
For example, ABCD*-+/
Algorithm:
1. Start
2. Push “(“onto Stack, and add “)” to the end of X.
3. Scan X from left to right and repeat Step 4 to 7 for each element of X until the Stack is empty.
4. If operator found, add it to Y.
5. And If left parenthesis found, push it onto Stack.
6. If an operator found ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has
the same precedence as or higher precedence than operator.
2. Add operator to Stack.
[End of If block]
7. If a right parenthesis found ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left
parenthesis is found.
2. Remove the left Parenthesis.
[End of If block]
[End of If block]
8. Stop
*Program to convert infix expression to postfix Expression
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
if(x == '^')
return 3;
return 0;
}
int main()
{
char exp[100];
char *e, x;
clrscr();
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else
{
if(*e == '(')
push(*e);
else
{
if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
{
printf("%c ",pop());
}
push(*e);
}
}
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}
getch();
return 0;
}
Out Put:1