28 Priyansh Exp-9

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Priyansh

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

int top = -1;

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;
}

void infixToPostfix(char *infix, char *postfix) {


char *e = infix;
int i = 0;
char x;

while (*e != '\0') {


if (isalnum(*e)) {
postfix[i++] = *e;
Priyansh
11723210028

} else if (*e == '(') {


push(*e);
} else if (*e == ')') {
while ((x = pop()) != '(') {
postfix[i++] = x;
}
} else {
while (top != -1 && priority(stack[top]) >= priority(*e)) {
postfix[i++] = pop();
}
push(*e);
}
e++;
}

while (top != -1) {


postfix[i++] = pop();
}

postfix[i] = '\0';
}

int main() {
char infix[MAX];
char postfix[MAX];

printf("Enter the Infix Expression: ");


scanf("%s", infix);

infixToPostfix(infix, postfix);
printf("Postfix Expression: %s\n", postfix);

return 0;
}

OUTPUT
Priyansh
11723210028

You might also like