#4 : Implementation of Infix to Postfix expression.

Implementation of Infix to Postfix expression.

Programming for Infix to Postfix expression.

Source Code.

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 30

char stack[SIZE]; int top=0;
char infix[SIZE];
char postfix[SIZE]; int p=0;

void in2po();
void push(char);
void pop(char);

int main()
{
	printf("infix: ");
	gets(infix);
	infix[strlen(infix)]='.';

	in2po();
	printf("postfix: ");
	puts(postfix);
        getch();
}

void push(char c)
{
	if(top!=SIZE)
	{
		stack[top]=c;
		top++;
	}
	else
	{
		printf("Stack Overflow\n");
		getch();
		exit(EXIT_FAILURE);
	}
}

void pop(char c)
{
	if(top<0)
	{
		printf("Stack empty\n");
		getch();
		exit(EXIT_FAILURE);
	}
	else
	{
		switch(c)
		{
			case '^':
				while( top>0 && stack[top-1]=='^' )
				{
					postfix[p]=stack[top-1];
					top--;
					p++;
				}
				break;
			case '/':
			case '*':
		while( top>0 && (stack[top-1]=='^' || stack[top-1]=='/') )
				{
					postfix[p]=stack[top-1];
					top--;
					p++;
				}
				break;
			case ')':
				while( top>0 && stack[top-1]!='(' )
				{
					postfix[p]=stack[top-1];
					top--;
					p++;
				}
				top--;
				break;
			case '.':
				while( top>0 )
				{
					postfix[p]=stack[top-1];
					top--;
					p++;
				}
				break;
		}
	}
}

void in2po()
{
	int i=0;
	char c;
	while(i<strlen(infix))
	{
		c = infix[i];
		switch(c)
		{
			case '+':
			case '-':
			case '(' :	push(c);
					break;
			case '.':
			case ')':
					pop(c);
					break;
			case '/':
			case '^':
			case '*':
					pop(c);
					push(c);
					break;
			default: postfix[p]=c; p++;
		}
		i++;
	}
}

Output.

infix: a+b+c
postfix: abc++

Or

infix: a-b+c
postfix: abc+-

Leave a Reply

Your email address will not be published. Required fields are marked *