C program to evaluate a postfix expression.

evaluate-postfix.c

C program to find out the value of an arithmetic expression in postfix (reverse polish) notation is as follows:

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

#define SIZE 100

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

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

void main()
{
	int i, j;
	int x, y, result, value;
	char postfix_exp[SIZE];
	char item;
	int data_values[SIZE];

	clrscr();

	printf("\nEnter the arithmetic expression in Postfix notation: \n");
	gets(postfix_exp);

	//Take the values of all operands from the user.
	i = 0;
	j = 0;
	item = postfix_exp[i++];
	while(item != '\0')
	{
		if(isalpha(item))
		{
			printf("\nEnter the value of operand %c: ",item);
			scanf("%d",&data_values[j++]);
		}
		item = postfix_exp[i++];
	}

	//Evaluate the postifx expression using a stack.
	i = 0;
	j = 0;
	item = postfix_exp[i++];
	while(item != '\0')
	{
		if(isalpha(item))
		{
			push(data_values[j++]);
		}
		else if(is_operator(item))
		{
			y = pop();
			x = pop();

			switch(item)
			{
				case '+':
					result = x + y;
					break;
				case '-':
					result = x - y;
					break;
				case '*':
					result = x * y;
					break;
				case '/':
					result = x / y;
					break;
				case '^':
					result = pow(x,y);
					break;
			}

			push(result);
		}
		else
		{
			printf("\nInvalid Postfix Expression.\n");
			getch();
			exit(0);
		}

		item = postfix_exp[i++];
	}

	value = pop();
	printf("\nValue of the postfix expression is %d.\n",value);
	getch();
}

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

//Function for pop operation
int pop()
{
	int 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;
	}
}