Data Structure lab

Program 4

Develop a Program in C for converting an Infix Expression to Postfix Expression. Program should support for both parenthesized and free parenthesized expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric operands.



#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

#define MAX 100

char stack[MAX];
int top = -1;

void push(char c) {
    stack[++top] = c;
}
char pop() {
    return (top == -1) ? '\0' : stack[top--];
}
char peek() {
    return (top == -1) ? '\0' : stack[top];
}

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

int isRightAssociative(char op) {
    return (op == '^');
}

void infixToPostfix(char *infix, char *postfix) {
    int i = 0, k = 0;
    char ch;
    while ((ch = infix[i++]) != '\0') {
        if (isalnum(ch)) {
            postfix[k++] = ch;
        }
        else if (ch == '(') {
            push(ch);
        }
        else if (ch == ')') {
            while (peek() != '(')
                postfix[k++] = pop();
            pop(); // remove '('
        }
        else { // operator
            while (precedence(peek()) > precedence(ch) ||
                  (precedence(peek()) == precedence(ch) && !isRightAssociative(ch))) {
                postfix[k++] = pop();
            }
            push(ch);
        }
    }
    while (top != -1)
        postfix[k++] = pop();
    postfix[k] = '\0';
}

int main() {
    char infix[MAX], postfix[MAX];
    printf("Enter Infix Expression: ");
    scanf("%s", infix);

    infixToPostfix(infix, postfix);

    printf("Postfix Expression is: %s\n", postfix);
    return 0;
}


               


  

Output :-

Enter Infix Expression: (A+B)*C^D    

Postfix Expression is: AB+CD^*
  
Comments

Replay !

0 Comments

Share Your Thoughts

Please enter your name
Please enter a valid email
Password must be at least 6 characters
Please enter your comment
Email Verification Required
We've sent a 6-digit verification code to . Please enter the code below to verify your email address.
Email Verified Successfully!
Your email has been verified. Would you like to proceed with posting your comment?

Type "YES" to confirm and post your comment, or click Cancel to skip posting.