Write a C program to convert Infix to Postfix Expression

C Program to convert infix expression to equivalent postfix



Problem Definition

We will be provied a infix expression and all we have to do is to convert that equation into its equivalent postfix expression using C Language.


Solution/Source Code

Here is the Souce C code to convert an infix expression to its equivalent postfix expression using stack. We will be using here few functions to impliment the code easily. The below code snippets are successfully compiled and runned on DEV C++ Windows 10 Platform. Output results are also shown below.



#include<stdio.h>
#include<string.h>
#define MAX 50
char stack[MAX];
int top=-1;
void push(char a){
	stack[++top]=a;
}
int pop(){
	return(stack[top--]);
}
int pre(char s){
	int a;
	switch(s){
		case '+':
		case '-':
			a=1;
			break;
		case '*':
		case '/':
		case '%':
			a=2;
			break;
		case '^':
			a=3;
			break;
	}
	return a;	
}
void intopost(char s[]){
	int i,j=-1;
	char s2[MAX];
	for(i=0;i<strlen(s);i++){
		if(s[i]=='(')
			push(s[i]);
		else if((s[i]>='0' & s[i]<='9') || (s[i]>='a' & s[i]<='z') || (s[i]>='A' & s[i]<='Z'))
			s2[++j]=s[i];
		else if(s[i]==')'){
			while(stack[top]!='(')
				s2[++j]=pop();
			if(stack[top]=='(')
				pop();
		}
		else{
			while((stack[top]!='(') & (pre(stack[top])>=pre(s[i])))
				s2[++j]=pop();
			push(s[i]);	
		}
	}	
	while(top!=-1)
		s2[++j]=pop();
	s2[++j]='\0';
	printf("\n---POSTFIX EXPRESSION---\n");
	puts(s2);
}
int main(){
	int len;
	char s[MAX];
	printf("Enter a Infix expression: ");
	gets(s);
	printf("\n---INFIX EXPRESSION---\n");
	puts(s);
	len=strlen(s);
	s[len]=')';
	s[len+1]='\0';
	push('(');
	intopost(s);
	return 0;
}
  

Output Test case 1:

Enter a Infix expression: ((3+6)*(2-4))+7

---INFIX EXPRESSION---
((3+6)*(2-4))+7

---POSTFIX EXPRESSION---
36+24-*7+

--------------------------------
  

Output Test case 2:

Enter a Infix expression: (a-b)*c+(d+e)

---INFIX EXPRESSION---
(a-b)*c+(d+e)

---POSTFIX EXPRESSION---
ab-c*de++

--------------------------------
  

Output Test case 3:

Enter a Infix expression: (a+b+c)

---INFIX EXPRESSION---
(a+b+c)

---POSTFIX EXPRESSION---
ab+c+

--------------------------------
  

Comments

Also Check Out

C Program to search element from a sorted array using Binary Search

C Program to Print Pascal's Triangle