May 11, 2023

Infix to Postfix Conversion

This is a description

Code

#include <stdio.h>

typedef struct {
    char arr[100];
    int top;
} Stack;
Stack stack;

int isOperand(char ch);
int isEmpty();
void push(int op);
char pop();
char top();
int precedence(char ch);
void display();

void main() {
    char infix[100], postfix[100];
    int i = 0, p = 0;
    char c;

    printf("Enter the infix expression: ");
    gets(infix);

    for (i = 0; infix[i] != '\0'; i++) {
        char ch = infix[i];

        if (isOperand(ch)) {
            postfix[p++] = ch;
        } else {
            if (ch == '(') {
                push(ch);
            } else if (ch == ')') {
                while ((c = pop()) != '(') {
                    postfix[p++] = c;
                }
            } else {
                if (precedence(ch) <= precedence(top())) {
                    postfix[p++] = pop();
                    push(ch);
                } else {
                    push(ch);
                }
            }
        }
    }

    while (!isEmpty()) {
        postfix[p++] = pop();
    }
    postfix[p] = '\0';
    display(&postfix);
}

int isOperand(char ch) {
    return ((ch >= 'A' && ch <= 'Z'));
}

int isEmpty() {
    return (stack.top == 0);
}

void push(int op) {
    stack.arr[++stack.top] = op;
}

char pop() {
    return stack.arr[stack.top--];
}

char top() {
    return stack.arr[stack.top];
}

int precedence(char ch) {
    switch (ch) {
        case '^': return 4;
        case '*':
        case '/':
        case '%': return 3;
        case '+':
        case '-': return 2;
        default: return 1;
    }
}

void display(char * ptr) {
    int i;
    printf("\nPostfix expression is: \n");
    for (i = 0; *(ptr+i) != '\0'; i++) {
        printf("%c", *(ptr+i));
    }
    printf("\n");
}