Question:

Write a program in C language to evaluate a Postfix expression by using a STACK Illustrate the algorithm with the help of an example?

by  |  earlier

0 LIKES UnLike

 Tags:

   Report

1 ANSWERS


  1. # include<stdio.h>
    # include<conio.h>
    # include<ctype.h>

    /*program to evaluate the given postfix expression*/

    typedef struct
    {
    int a[100];
    int top;
    }

    STACK;

    void push(STACK *s,int x)
    {
    if(s->top==99)
    printf("STACK OVERFLOW\n");
    else
    s->a[++s->top]=x;
    }

    int pop(STACK *s)
    {
    int x;
    if(s->top<0)
    {
    printf("STACK UNDERFLOW\n");
    }
    else
    {
    x=s->a[s->top--];
    }
    return x;
    }

    int operation(int p1,int p2,char op)
    {
    int x;

    switch(op)
    {
    case '+':
    x= p1+p2;
    case '*':
    x= p1*p2;
    case '-':
    x= p1-p2;
    case '/':
    x= p1/p2;
    }
    return x;
    }


    int evaluate(char pos[])
    {
    STACK s1;
    int p1,p2,result,i;
    s1.top=-1;

    for(i=0;pos[i]!='\0';i++)
    if(isdigit(pos[i]))
    push(&s1,pos[i]-'0'); /*use to find the integer value of it*/

    else
    {
    p2=pop(&s1);
    p1=pop(&s1);
    result=operation(p1,p2,pos[i]);
    push(&s1,result);
    }/*end of for loop*/ return pop(&s1);
    }

    void main()
    {
    char postfix[100];
    clrscr();
    printf("Please Enter the VALID POSTFIX string\n\n Operands are SINGLE DIGIT\n\n");

    gets(postfix);
    printf("The Result is==>%d",evaluate(postfix));

    getch();

    }/*end of main*/

    /*
    Algorithm: Postfix Expression :Algorithm STEP 1 : Read the given postfix expression into a string called postfix. STEP 2 : Read one character at a time & perform the following operations : 1. If the read character is an operand, then convert it to float and push it onto the stack. 2. If the character is not an operand, then pop the operator from stack and assign to OP2. Similarly, pop one more operator from stack and assign to OP1. 3. Evaluate the result based on operator x. 4. Push the result (based on operator x) onto the stack. STEP 3 : Repeat STEP 2 till all characters are processed from the input string. STEP 4 : Return the result from this procedure or algorithm and display the result in main program.
    */

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.