Postfix Evaluation Process

 avatar
unknown
c_cpp
a year ago
2.1 kB
5
Indexable
//Program Structure of Postfix Evaluation Process
#include <stdio.h>
#include <math.h>

#define MAX_SIZE 100

int top = -1;
int stack[MAX_SIZE];

void push(int);
int pop();
int eval(char, int, int);

int main() {
    int i, op1, op2, res;
    char a[50], ch;

    printf("Enter a postfix expression: ");
    scanf("%[^\n]s", a);

    for (i = 0; a[i] != '\0'; i++) {
        ch = a[i];
        if (ch >= '0' && ch <= '9') {
            push(ch - '0'); // Push operand onto the stack
        } else if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^') {
            // Perform postfix evaluation steps
            op2 = pop();
            op1 = pop();
            if (op1 == -1 || op2 == -1) {
                printf("Invalid expression.\n");
                return 1;
            }
            res = eval(ch, op1, op2);
            push(res);
        }
    }

    if (top == 0) {
        res = pop();
        printf("Result: %d\n", res);
    } else {
        printf("Invalid expression.\n");
    }

    return 0;
}

void push(int n) {
    if (top < MAX_SIZE - 1) {
        top++;
        stack[top] = n;
    } else {
        printf("Stack overflow.\n");
    }
}

int pop() {
    if (top >= 0) {
        int item = stack[top];
        top--;
        return item;
    } else {
        printf("Stack underflow.\n");
        return -1;
    }
}

int eval(char ch, int op1, int op2) {
    int result;
    switch (ch) {
        case '+':
            result = op1 + op2;
            break;
        case '-':
            result = op1 - op2;
            break;
        case '*':
            result = op1 * op2;
            break;
        case '/':
            if (op2 != 0) {
                result = op1 / op2;
            } else {
                printf("Division by zero.\n");
                return -1;
            }
            break;
        case '^':
            result = pow(op1, op2);
            break;
        default:
            printf("Invalid operator.\n");
            return -1;
    }
    return result;
}

/*
Enter a postfix expression: str = " 2 3 1 * + 9 - "
Result: -4
*/
Leave a Comment