The greatest mistake you can make in life is to be continually fearing you will make one

Wednesday, 15 June 2011

C program for Evaluating a Postfix Expression

The Algorithm for Evaluating a Postfix Expression  is given here

Program:

#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define SIZE 40
int stack[SIZE];
int top=-1;

void push(int n)
{
    if(top==SIZE-1)
    {
        printf("Stack is full\n");
        return;
    }
    else
    {
        top=top+1;
        stack[top]=n;
        printf("Pushed element is %d\n",n);
    }
}

int pop()
{
    int n;
    if(top==-1)
    {
        printf("Stack is empty\n");
        return;
    }
    else
    {
        n=stack[top];
        top=top-1;
        printf("The poped element is %d\n",n);
        return(n);
    }
}

int evaluate(int op1, int op2,char ch)
{
    printf("op1=%d op2=%d ch=%c\n",op1,op2,ch);
    int n;
    if (op1<op2)
    {
        n=op1;
        op1=op2;
        op2=n;
        }
    if(ch=='+')
        n=op1+op2;
    else if(ch=='-')
        n=op1-op2;
    else if(ch=='*')
        n=op1*op2;
    else if(ch=='/')
        n=op1/op2;
    else if(ch=='%')
        n=op1%op2;
    else
    {
        printf("The operator is not identified\n");
        exit(0);
    }
    printf("n=%d\n",n);
    return(n);
}

int main()
{
      char str[50],ch,ch1;
      int i=0,n,op1,op2;

      printf("Enter the Postfix string\n");
      scanf("%s",str);
      ch=str[i];
      while(ch!='\0')
      {
        printf("The char is=%c\n",ch);
           //if(ch=='1' || ch=='2' || ch=='3' || ch=='4' || ch=='5')//
           if(isdigit(ch))
           {
                n=ch-'0';
                push(n);
           }
           else
           {
                op1=pop();
                op2=pop();
                n=evaluate(op1,op2,ch);
                push(n);
           }
           ch=str[++i];
      }
      printf("The value of the arithmetic expression is=%d\n",pop());
      return;
}

9 comments:

  1. do not swap the operands it will affect the division

    ReplyDelete
  2. not only in swapping but also in other operations

    ReplyDelete
  3. actually...swapping the operands does not affect any operation. either 4 8 / or 8 4 / returns 2. Although it wouldve been nicer if this program worked for multiple digit numbers also.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. Hey Buddy.
    Tried your program. It works great I guess.
    You can compare it with my program here

    Click Me

    ReplyDelete
  6. It does not work for multiple digits.

    ReplyDelete
  7. Thank you very very very very very much ...,

    ReplyDelete
  8. Great! Thanks a lot! :) The best answer for my assignment.

    ReplyDelete
  9. Good
    Here is a link for C/C++ programs and pointer programs. This may be useful for you.

    C Programs

    C++ Programs

    ReplyDelete