Blogger news

Followers

Thursday, September 26, 2013
Design, develop and execute a program in C to Evaluate a valid postfix expression using stack. Assume that the postfix expression is read as a single line consisting of non-negative single digit operands and binary arithmetic operators. The arithmetic operators are +(add),-(subtract),*(multiply) and / (divide)

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

 char postfix[20];
 int top=-1;
 float value[20],stack[20];
 float eval();

 void push(float);
 float pop();

 void main()
 {
  int i=0;
  float result;
  clrscr();

  printf("enter a valid postfix expression\n");
  scanf("%s",postfix);
  while(postfix[i]!='\0')
  {
    if(isalpha(postfix[i]))
    {
     printf("enter the value of %c\n",postfix[i]);
     scanf("%f",&value[i]);
    }
   i++;
  }
  result=eval();
  printf("the value of the expression is %.2f\n",result);

  getch();
 }

 float eval()
 {
  int i=0;
  float op1,op2,result;

  while(postfix[i]!='\0')
  {
    if(isalpha(postfix[i]))
      push(value[i]);
    else
    {
      op2=pop();
      op1=pop();

      switch(postfix[i])
      {
                case'+':
                       push(op1+op2);
                       break;
                case'-':
                       push(op1-op2);
                       break;
                case'*':
                       push(op1*op2);
                       break;
                case'/':
                       push(op1/op2);
                       break;
      };
    }
   i++;
  }
 result=pop();
 return result;
}

void push(float value)
{
  top=top+1;
  stack[top]=value;
  return;
}


float pop()
{
  return stack[top--];
}
Screenshot:

1 comments:

sharma said...

algorithm?