28 Priyansh Exp-9
28 Priyansh Exp-9
28 Priyansh Exp-9
11723210028
EXPERIMENT 9
AIM: Write a program in C to convert infix to postfix expression using stacks.
ALGORITHM
● Infix to Postfix Conversion Using Stacks
● Initialize:
● • Create an empty stack for operators.
● • Create an empty list for the postfix expression.
● 2. For each character ch in the infix expression:
● • If ch is an operand, add it to the postfix
expression.
● • If ch is (, push it onto the stack.
● • If ch is ), pop from the stack to the postfix
expression until ( is encountered, then discard (.
● • If ch is an operator:
● • Pop operators from the stack to the postfix
expression while they have greater or equal precedence than
ch.
● • Push ch onto the stack.
3. Pop all remaining operatorsfrom the stack and append
to the postfix expression.
4. Return the postfix expression.
CODE
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#define MAX 20
char stack[MAX];
Priyansh
11723210028
void push(char x) {
if (top < MAX - 1) {
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;
}
return -1;
}
postfix[i] = '\0';
}
int main() {
char infix[MAX];
char postfix[MAX];
infixToPostfix(infix, postfix);
printf("Postfix Expression: %s\n", postfix);
return 0;
}
OUTPUT
Priyansh
11723210028