Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

infix to postfix conversion in C

#include<stdio.h>
#include<stdlib.h>
#define Blank ' '
#define Tab '\t'
#define MAX 100

long int pop ();
char infix[MAX], postfix[MAX];
long int stack[MAX];
int top;

void main()
{
long int value;
char choice='y';
clrscr();
while(choice == 'y')
{
top = 0;
printf("Enter infix : ");
fflush(stdin);
gets(infix);
infix_to_postfix();
printf("Postfix : %s\n",postfix);
printf("Want to continue(y/n) : ");
scanf("%c",&choice);
}
}

infix_to_postfix()
{
int i,p=0,type,precedence,len;
char next ;
stack[top]='#';
len=strlen(infix);
infix[len]='#';
for(i=0; infix[i]!='#';i++)
{
if( !white_space(infix[i]))
{
switch(infix[i])
{
case '(':
push(infix[i]);
break;

case ')':
while((next = pop()) != '(')
postfix[p++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
precedence = prec(infix[i]);
while(stack[top]!='#' && precedence<= prec(stack[top]))
postfix[p++] = pop();
push(infix[i]);
break;
default: /*if an operand comes */
postfix[p++] = infix[i];
}/*End of switch */
}/*End of if */
}/*End of for */
while(stack[top]!='#')
postfix[p++] = pop();
postfix[p] = '\0' ;  /*End postfix with'\0' to make it a string*/
}

prec(char symbol )
{
switch(symbol)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
}
}

push(long int symbol)
{
if(top > MAX)
{
printf("Stack overflow\n");
exit(1);
}
else
{
top=top+1;
stack[top] = symbol;
}
}

long int pop()
{
if (top == -1 )
{
printf("Stack underflow \n");
exit(2);
}
else
return (stack[top--]);
}

white_space(char symbol)
{
if( symbol == Blank || symbol == Tab || symbol == '\0')
return 1;
else
return 0;
}