Implementation of Infix to Postfix expression

In this article we will see Implementation of Infix to Postfix expression

Implementation of Infix to Postfix expression

infix to postfix

Also, you can use the C compiler to compile a program.

Read more: – Double Ended Queue or Deque

Source Code of infix to postfix in C

#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++; 
	} 
}

 

Related: – Stack using Linked List.

Output.

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

Or

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

About Ashishkumar Vishwakarma

I am Ashish- a Developer live in Mumbai.

View all posts by Ashishkumar Vishwakarma →

One Comment on “Implementation of Infix to Postfix expression”

Leave a Reply