Home / Research Papers / IT/Technology / Conversion of Infix Expression to Postfix Expression

Conversion of Infix Expression to Postfix Expression

Assignment : Data structure

Conversion of infix expression to postfix expression

#include”stdio.h”

#include “stdafx.h”

#include”conio.h”

#include”iostream”

#include”stdlib.h”

#include”string.h”

using namespace std;

# define MAX 100

int top=-1;

char infix[100],postfix[100];

char stack[100];

int priority(char symbol)

{

switch(symbol)

{

case ‘(‘:return 0;

case ‘+’:

case ‘-‘:

return 1;

case ‘/’:

case ‘*’:

case ‘%’:

return 2;

case ‘^’:

return 3;

default :return 0;

}

}

void push(char symbol)

{

if(top==MAX-1)

{

cout<<“Stack overflow:\n”;

exit(1);

}

top=top+1;

stack[top]=symbol;

}

char pop()

{

if(top==-1)

{

cout<<“Stack underflow:\n”;

exit(1);

}

return stack[top–];

}

void infix_to_postfix()

{

int i,p=0;

char symbol,next;

for(i=0;i<strlen(infix);i++)

{

symbol=infix[i];

switch(symbol)

{

case ‘(‘:push(symbol);

break;

case ‘)’:while((next=pop())!='(‘)

{

postfix[p]=next;

p++;

}

break;

case ‘+’:

case ‘-‘:

case ‘*’:

case ‘/’:

case ‘%’:

case ‘^’:

while(top!=-1 && priority(stack[top])>=priority(symbol))

{//or stack is empty

postfix[p]=pop();

p++;

}

push(symbol);

break;

default://if operand comes

postfix[p]=symbol;

p++;

}

}

while(top!=-1)

{

postfix[p]=pop();

//printf(“%c”,pop());

p++;

}

postfix[p]=’\0′;

}

int main()

{

cout<<“Enter the infix expression:\n”;

cin>>infix;

cout<<“The post fix expression is:\n”;

infix_to_postfix();

printf(“->  %s”,postfix);

getch();

return 0;

}

Conversion of Infix Expression to Postfix Expression

Leave a Reply

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