Evaluate a postfix and prefix equation program in c programming
February 18, 2023

Evaluate a Postfix and Prefix equation program in c

In this tutorial post, we are going to write to evaluate a postfix and prefix equation program in c programming.

#define MAXSTK 10
struct stack
{
    int top;
    int data[MAXSTK];
};

void push(struct stack *, int );
int pop(struct stack *);
int isoperator(char);
int evalpost(char []);
int evalpre(char []);
int eval(char, int, int);

void main()
{
    char post[50],pre[50];
    int ans;
    clrscr();
    printf("Enter string in postfix form");
    gets(post);
    ans = evalpost(post);
    printf("Result of post eq is %d\n", ans);
    printf("Enter string in prefix form");
    gets(pre);
    ans = evalpre(pre);
    printf("Result of pre eq is %d\n", ans);
    getch();
}

void push(struct stack *p, int item)
{
    if(p -> top == MAXSTK-1)
    {
        printf("Overflow");
        exit(0);
    }
    p->top++;
    p->data[p->top] = item;
}

int pop(struct stack *p)
{
    int item;
    if(p-> top == -1)
    {
        printf("Underflow");
        exit(0);
    }
    item = p->data[p->top];
    p->top--;
    return(item);
}

int isoperator(char ch)
{
    if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%')
        return(1);
    else
        return(0);
}

int eval(char op, int op1, int op2)
{
    switch(op)
    {
        case '+': return(op1+op2);
        case '-': return(op1-op2);
        case '*': return(op1*op2);
        case '/': return(op1/op2);
        default: return(0);
    }
}

int evalpost(char post[])
{
    struct stack s1;
    int i,a,b,ans;
    s1.top = -1;
    i=0;

    while(post[i] != '\0')
    {
        if(isoperator(post[i]))
        {
            b = pop(&s1);
            a = pop(&s1);
            ans = eval(post[i],a,b);
            push(&s1,ans);
        }
        else
            push(&s1,post[i] - '0');
        i++;
    }
    ans = pop(&s1);
    return(ans);
}

int evalpre(char pre[])
{
    struct stack s1;
    int i,a,b,ans;
    s1.top = -1;
    i=0;

    while(pre[i] != '\0')
        i++;
    i--;

    while(i >= 0)
    {
        if(isoperator(pre[i]))
        {
            a = pop(&s1);
            b = pop(&s1);
            ans = eval(pre[i],a,b);
            push(&s1,ans);
        }
        else
            push(&s1,pre[i] - '0');
        i--;
    }
    ans = pop(&s1);
    return(ans);
}