Postfix expression using stack

 Aim

To implement a program in C to evaluate a postfix expression using stack.

Objective

  • To understand the use of stack in expression evaluation.

  • To apply stack operations (push and pop) in postfix evaluation.

  • To evaluate arithmetic expressions given in postfix form.

Algorithm

  1. Start.

  2. Read the postfix expression from left to right.

  3. If the character is an operand (number):
    → Push it onto the stack.

  4. If the character is an operator (+, -, *, /, ^):
    → Pop the top two elements from stack.
    → Apply the operator: result = operand2 operator operand1
    → Push the result back onto the stack.

  5. Repeat until the expression ends.

  6. The final element left in the stack is the result of the expression.

  7. End.

Flowchart:

Generated image

C Program – Postfix Evaluation Using Stack

#include <stdio.h>

#include <ctype.h>   // for isdigit()

#include <stdlib.h>  // for atoi()

#define MAX 100

int stack[MAX];

int top = -1;

// Push element into stack

void push(int val) {

    if (top == MAX - 1) {

        printf("Stack Overflow\n");

        return;

    }

    stack[++top] = val;

}

// Pop element from stack

int pop() {

    if (top == -1) {

        printf("Stack Underflow\n");

        exit(1);

    }

    return stack[top--];

}

// Evaluate Postfix Expression

int evaluatePostfix(char postfix[]) {

    int i;

    for (i = 0; postfix[i] != '\0'; i++) {

        char ch = postfix[i];

        if (isdigit(ch)) {

            // convert character digit to int and push

            push(ch - '0');

        } 

        else {

            // Operator: pop 2 operands

            int val1 = pop();

            int val2 = pop();

            int result;

            switch (ch) {

                case '+': result = val2 + val1; break;

                case '-': result = val2 - val1; break;

                case '*': result = val2 * val1; break;

                case '/': result = val2 / val1; break;

                default: 

                    printf("Invalid Operator\n");

                    exit(1);

            }

            push(result);

        }

    }

    return pop();

}

// Driver Program

int main() {

    char postfix[100];

    printf("Enter a Postfix Expression: ");

    scanf("%s", postfix);

    int result = evaluatePostfix(postfix);

    printf("Result of Postfix Evaluation: %d\n", result);

    return 0;

}


Comments

Popular posts from this blog

Stack using array

Bubble Sort

Singly linked list implementation