C program to convert from Infix to Postfix.

infix-to-postfix.c

C program to convert an arithmetic expression given in Infix notation to Postfix notation is as follows:

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

#define SIZE 100

int top = -1;
char stack[SIZE];

//Function prototypes
void push(char item);
char pop();
int is_operator(char symbol);
int precedence(char symbol);

void main()
{
	int i, j;
	char infix_exp[SIZE], postfix_exp[SIZE];
	char item, x;
	clrscr();

	printf("\nEnter the arithmetic expression in Infix notation enclosed in parentheses: \n");
	gets(infix_exp);

	i = 0;
	j = 0;
	item = infix_exp[i++];
	//Read symbol from Input string one at a time.
	while(item != '\0')
	{
		//If the symbol is left parenthesis
		if(item == '(')
		{
			push(item);
		}
		//If the symbol is an operand
		else if((item >= 'A'  && item <= 'Z') || (item >= 'a' && item <= 'z'))
		{
			postfix_exp[j++] = item;
		}
		//If the symbol is an operator
		else if(is_operator(item) == 1)
		{
			x = pop();
			while(is_operator(x) == 1 && precedence(x) >= precedence(item))
			{
				postfix_exp[j++] = x;
				x = pop();
			}
			push(x);
			push(item);			
		}
		//If the symbol is a right parenthesis
		else if(item == ')')
		{
			x = pop();
			while(x != '(')
			{
				postfix_exp[j++] = x;
				x = pop();
			}
		}
		//If the symbol is any other invalid character
		else
		{
			printf("\nInvalid Arithmetic Expression.\n");
			getch();
			exit(0);
		}

		item = infix_exp[i++];
	}

	postfix_exp[j++] = '\0';
	printf("\nArithmetic expression in Postfix notation: ");
	puts(postfix_exp);

	getch();
}

//Function for push operation
void push(char item)
{
	if(top >= SIZE-1)
	{
		printf("\nStack Overflow. Push not possible.\n");
	}
	else
	{
		top = top+1;
		stack[top] = item;
	}
}

//Function for pop operation
char pop()
{
	char item = NULL;

	if(top <= -1)
	{
		printf("\nStack Underflow. Pop not possible.\n");
	}
	else
	{
		item = stack[top];
		stack[top] = NULL;
		top = top-1;
	}
	return(item);
}

//Function to check whether the symbol is an operator.
int is_operator(char symbol)
{
	if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol == '-')
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

//Function which returns the precedence of the operator.
int precedence(char symbol)
{
	if(symbol == '^')
	{
		return(3);
	}
	else if(symbol == '*' || symbol == '/')
	{
		return(2);
	}
	else if(symbol == '+' || symbol == '-')
	{
		return(1);
	}
	else
	{
		return(0);
	}
}