Friday, 25 April 2014

Infix to postfix calculator in c

#define SIZE 50            /* Size of Stack */
char s[SIZE];
float ss[SIZE];
int top = -1; /* Global declarations */
float push1(float elem) { /* Function for PUSH operation */
 ss[++top] = elem;
}

float pop1() { /* Function for POP operation */
 return (ss[top--]);
}


float calculator(char pofx[])/* Evaluation of post fix*/
{  top=-1;
      float a,b,result,x;int i=0;char ch;
    while(pofx[i]!='\0')
    {  ch=pofx[i];
        switch(ch)
        {
            case '+':
                    b=pop1();
                    a=pop1();
                    result=(float)(a+b);
                    push1(result);
                    break;
            case '-':
                    b=pop1();
                    a=pop1();
                    result=(float)(a-b);
                    push1(result);
                    break;
            case '*':
                    b=pop1();
                    a=pop1();
                    result=(a*b);
                    push1(result);
                    break;
            case '/':
                    b=pop1();
                    a=pop1();
                    result=(a/b);
                    push1(result);
                    break;
            default:
                   x=(float)ch-'0';
                    push1(x);
            }
         i++;
    }
    return result;
}
int pr(char elem) { /* Function for precedence */
 switch (elem) {
 case '#':
  return 0;
 case '(':
  return 1;
 case '+':
 case '-':
  return 2;
 case '*':
 case '/':
 case '%':
  return 3;
 }
}
void push(char elem) { /* Function for PUSH operation */
 s[++top] = elem;
}

char pop() { /* Function for POP operation */
 return (s[top--]);
}
void convert(char infx[], char pofx[])
{
    char ch, elem;
 int i = 0, k = 0;
    push('#');
 while ((ch = infx[i++]) != '\0') {
  if (ch == '(')
   push(ch);
  // else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%')
  else if ( ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%')
    {
        while (pr(s[top]) >= pr(ch))
    pofx[k++] = pop();
   push(ch);
    }
  else if (ch == ')')
    {
   while (s[top] != '(')
    pofx[k++] = pop();
   elem = pop(); /* Remove ( */
  }
  else { /* Operator */
   pofx[k++] = ch;
  }
 }
 while (s[top] != '#') /* Pop from stack till empty */
  pofx[k++] = pop();
 pofx[k] = '\0'; /* Make pofx as valid string */


}

main() { /* Main Program */
 char infx[50], pofx[50], ch, elem;
 int i = 0, k = 0;
 printf("\n\nRead the Infix Expression ? ");
 scanf("%s", infx);
 convert(infx,pofx);
  printf("\n\nGiven Infix Expn: %s  Postfix Expn: %s\n", infx, pofx);
  printf("%f",calculator(pofx));
}