Program Structure of Postfix Evaluation Process

 avatar
shebom640
c_cpp
a year ago
2.8 kB
5
Indexable
// QUESTION 2
//Program Structure of Postfix Evaluation Process

#include <stdio.h>
#include<math.h>
int top = -1, stack [100];
void push (int);
int pop( );
int eval (char, int, int);
int main ( ){
int i,op1,op2,res,x,j;
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');
}
else{
// Pop and store in op2
//Pop and store in op1
//call eval method store the result in res
//push the res in the stack
}
}
//Final pop operation to get the result and print the value
return 0;
}
void push (int n){
//Push algorithm
}
int pop ( ){
Pop algorithm
}
int eval (char ch, int op1, int op2){
switch (ch){
//Consider addition, subtraction, multiplication, division and exponential operation
}
}




// ANSWER
#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;
}