google.com, pub-4617457846989927, DIRECT, f08c47fec0942fa0 Learn to enjoy every minute of your life.Only I can change my life.: C program in stack data structure for infix and postfix expression

Wednesday, April 1, 2015

C program in stack data structure for infix and postfix expression

#define max 50
#include<stdio.h>
#include<conio.h>
#include<process.h>
void push(char ch);
char pop();
char stack[max];
int top=-1;
int prec(char chr);
void main()
{
 char a[60],b[60],ch;
 int i,j,p,r,x,y,re;
 clrscr();
 printf("\n Enter Infix Expression:-\n");
 scanf("%s",&a);
 i=0;
 j=0;
 for(i=0;a[i]!='\0';i++)
 {
  switch(a[i])
  {
   case '^':
   case '$':
   case '*':
   case '/':
   case '+':
   case '-': p=prec(a[i]);
    while(top!=-1&&p<=prec(stack[top]))
    {
      b[j]=pop();
      j++;
    }
    push(a[i]);  //push operator into stack
    break;
   case '(': push(a[i]);
    break;

   case ')':
    do
    {
     ch=pop();
     if(ch!='(')
     {
      b[j]=ch;
      j++;
     }
    }while(ch!='(');
     break;
   default : b[j]=a[i];  //output exp
    j++;
  }
 }
 while(top!=-1)
 {
  b[j]=pop();  //last pop the all operators.
  j++;
 }
 b[j]='\0';
 printf("\n Postfix Expression Is:-\n %s",b);
 printf("\n Evaluation of the Postfix expression:-\n");
 i=0;
 while(b[i]!='\0')
 {
  if(b[i]>='0'&&b[i]<='9')
  {
   push(b[i]-48); //convert char into nuumber
  }
  else
  {
   y=pop(); //pop the two poerands and prefrom operation
   x=pop();
   switch(b[i])
   {
      case '+' : r=x+y;
break;
      case '-' : r=x-y;
break;
      case '*' : r=x*y;
break;
      case '/' : r=x/y;
break;
      case '$' :
      case '^' : r=pow(x,y);
break;
   }
   push(r); //push the result into stack
  }
  i++;
 }
 re=pop(); // at the last pop the result and display.
 printf("\n %d",re);
 getch();
}

int prec(char chr)
{
 switch(chr)   // check the priority of the operators.
 {
  case '$' :
  case '^' : return(5);
  case '*' :
  case '/' : return(4);
  case '+' :
  case '-' : return(3);
  case '(' : return(2);
 }
 return(0);
}
void push(char x)
{
  top++;
  stack[top]=x;
}
char pop()
{
 char y;
 y=stack[top];
 top--;
 return(y);
}



शिव भोलेनाथ स्तुति

 जय शिवशंकर, जय गंगाधर, करुणा-कर करतार हरे,   जय कैलाशी, जय अविनाशी, सुखराशि, सुख-सार हरे जय शशि-शेखर, जय डमरू-धर जय-जय प्रेमागार हरे,   जय ...