You are on page 1of 5

Infix to Postfix

Program :
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>

#define MAX 100


void InfixPostfix(char infix[], char postfix[]);
int stack[MAX];
int top=-1;
void push(int x);
int isEmpty();
int pop();

void main(){

char infix[20], postfix[20];


int result;
clrscr();

printf("\n*****INFIX TO POSTFIX USING STACK*****\n");

printf("\nEnter Infix Expression: ");


scanf("%s",infix);
InfixPostfix(infix,postfix);
printf("\nPost Expression: %s",postfix);
getch();
}

void InfixPostfix(char infix[], char postfix[]){


int i,j=0;
for(i=0;infix[i]!='\0';i++){
if(isalpha(infix[i]) || isdigit(infix[i])){

postfix[j++] = infix[i];
}
else if(infix[i] =='('){
push(infix[i]);
}
else if(infix[i] ==')'){
while(stack[top] !='('){
postfix[j++]=pop();
}
pop();
}
else{
while((!isEmpty() && stack[top] !='(') &&
(priority(stack[top])>=priority(infix[i]))){
postfix[j++] = pop();
}
push(infix[i]);
}
}
while(!isEmpty() && stack[top]!='('){
postfix[j++]=pop();
}
postfix[j]='\0';
}

int priority(char ch){


if(ch=='*' || ch=='/'){
return 2;
}
if(ch =='+' || ch=='-'){
return 1;

int isEmpty(){
if(top==-1){
return 1;
}
else{
return 0;
}
}
void push(int x){

if(top==MAX-1){
printf("\nStack is Overflow ");
}
else{
top++;
stack[top] = x;
}
}

int pop(){
int n;
if(isEmpty()){
return -1;
}
else{
n=stack[top];
top--;
return n;
}
}

// void peek(){
// if(top==-1){
// printf("\nStack is Empty ");
// }
// else{
// printf("\nTop Element is : %d",stack[top]);
// }
// }

// void display(){
// int i;

// if(top==-1){
// printf("Stack is Empty");
// }

// printf("\n The elements in Stack: ");


// for(i=top;i>=0;i--){
// printf(" %d",stack[i]);
// }

// }

You might also like