0% found this document useful (0 votes)
80 views23 pages

Infix to Postfix and Prefix Conversion

The document contains code for converting an infix expression to postfix notation and then evaluating the postfix expression. It defines functions for operations on a stack like push(), pop() and functions for checking operator precedence and whether a symbol is an operator. The infixToPostfix function uses these functions to convert an infix string to postfix by traversing the string and pushing/popping from the stack based on the symbol type. The postfix expression is then evaluated by traversing it and pushing operands and popping for operators.

Uploaded by

lokeshkumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views23 pages

Infix to Postfix and Prefix Conversion

The document contains code for converting an infix expression to postfix notation and then evaluating the postfix expression. It defines functions for operations on a stack like push(), pop() and functions for checking operator precedence and whether a symbol is an operator. The infixToPostfix function uses these functions to convert an infix string to postfix by traversing the string and pushing/popping from the stack based on the symbol type. The postfix expression is then evaluated by traversing it and pushing operands and popping for operators.

Uploaded by

lokeshkumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include<stdio.

h>

#include<stdlib.h> /* for exit() */

#include<ctype.h> /* for isdigit(char ) */

#include<string.h>

#define SIZE 100

char stack[SIZE];

int top = -1;

/* define push operation */

void push(char item)

if(top >= SIZE-1)

printf("\nStack Overflow.");

else

top = top+1;

stack[top] = item;

/* define pop operation */

char pop()

char item ;

if(top <0)
{

printf("stack under flow: invalid infix expression");

getchar();

/* underflow may occur for invalid expression */

/* where ( and ) are not matched */

exit(1);

else

item = stack[top];

top = top-1;

return(item);

/* define function that is used to determine whether any symbol is operator or not

(that is symbol is operand)

* this fucntion returns 1 if symbol is opreator else return 0 */

int is_operator(char symbol)

if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-')

return 1;

else

{
return 0;

/* define fucntion that is used to assign precendence to operator.

* Here ^ denotes exponent operator.

* In this fucntion we assume that higher integer value

* means higher precendence */

int precedence(char symbol)

if(symbol == '^')/* exponent operator, highest precedence*/

return(3);

else if(symbol == '*' || symbol == '/')

return(2);

else if(symbol == '+' || symbol == '-') /* lowest precedence */

return(1);

else

return(0);

}
}

void InfixToPostfix(char infix_exp[], char postfix_exp[])

int i, j;

char item;

char x;

push('('); /* push '(' onto stack */

strcat(infix_exp,")"); /* add ')' to infix expression */

i=0;

j=0;

item=infix_exp[i]; /* initialize before loop*/

while(item != '\0') /* run loop till end of infix expression */

if(item == '(')

push(item);

else if( isdigit(item) || isalpha(item))

postfix_exp[j] = item; /* add operand symbol to postfix expr */

j++;

else if(is_operator(item) == 1) /* means symbol is operator */


{

x=pop();

while(is_operator(x) == 1 && precedence(x)>= precedence(item))

postfix_exp[j] = x; /* so pop all higher precendence


operator and */

j++;

x = pop(); /* add them to postfix expresion */

push(x);

/* because just above while loop will terminate we have

oppped one extra item

for which condition fails and loop terminates, so that one*/

push(item); /* push current oprerator symbol onto stack */

else if(item == ')') /* if current symbol is ')' then */

x = pop(); /* pop and keep popping until */

while(x != '(') /* '(' encounterd */

postfix_exp[j] = x;

j++;

x = pop();

else

{ /* if current symbol is neither operand not '(' nor ')' and nor
operator */

printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */

getchar();

exit(1);

i++;

item = infix_exp[i]; /* go to next symbol of infix expression */

} /* while loop ends here */

if(top>0)

printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */

getchar();

exit(1);

if(top>0)

printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */

getchar();

exit(1);

postfix_exp[j] = '\0'; /* add sentinel else puts() fucntion */

/* will print entire postfix[] array upto SIZE */


}

/* main function begins */

int main()

char infix[SIZE], postfix[SIZE]; /* declare infix string and postfix string */

/* why we asked the user to enter infix expression

* in parentheses ( )

* What changes are required in porgram to

* get rid of this restriction since it is not

* in algorithm

* */

printf("ASSUMPTION: The infix expression contains single letter variables and single digit
constants only.\n");

printf("\nEnter Infix expression : ");

gets(infix);

InfixToPostfix(infix,postfix); /* call to convert */

printf("Postfix Expression: ");

puts(postfix); /* print postfix expression */

return 0;

}
Infix to prefix

#include<stdio.h>

#include<stdlib.h>

#include<math.h>

#include<string.h>

int pop();

int precedence(char symbol);

int isEmpty();

void infix_to_prefix();

int checker(char symbol);

void push(long int symbol);

char prefix_string[20], infix_string[20], postfix_string[20];

int top;

long int stack[20];

int main()

int count, length;

char temp;

top = -1;

printf(“\nEnter an Expression in Infix format:\t”);

scanf(“%[^\n]s”, infix_string);

infix_to_prefix();

printf(“\nExpression in Postfix Format: \t%s\n”, postfix_string);

length = strlen(postfix_string) – 1;
strncpy(prefix_string, postfix_string, 20);

for(count = 0; count < length; count++, length–)

temp = prefix_string[count];

prefix_string[count] = prefix_string[length];

prefix_string[length] = temp;

printf(“\nExpression in Prefix Format: \t%s\n”, prefix_string);

return 0;

void infix_to_prefix()

unsigned int count, temp = 0;

char next;

char symbol;

for(count = 0; count < strlen(infix_string); count++)

symbol = infix_string[count];

if(!checker(symbol))

switch(symbol)

case ‘(‘: push(symbol);

break;

case ‘)’:

while((next = pop()) != ‘(‘)


{

postfix_string[temp++] = next;

break;

case ‘+’:

case ‘-‘:

case ‘*’:

case ‘/’:

case ‘%’:

case ‘^’:

while(!isEmpty() && precedence(stack[top]) >= precedence(symbol))

postfix_string[temp++] = pop();

push(symbol);

break;

default:

postfix_string[temp++] = symbol;

while(!isEmpty())

postfix_string[temp++] = pop();

postfix_string[temp] = ‘\0’;

int precedence(char symbol)

{
switch(symbol)

case ‘(‘: return 0;

case ‘+’:

case ‘-‘:

return 1;

case ‘*’:

case ‘/’:

case ‘%’:

return 2;

case ‘^’:

return 3;

default:

return 0;

int checker(char symbol)

if(symbol == ‘\t’ || symbol == ‘ ‘)

return 1;

else

return 0;

}
void push(long int symbol)

if(top > 20)

printf(“Stack Overflow\n”);

exit(1);

top = top + 1;

stack[top] = symbol;

int isEmpty()

if(top == -1)

return 1;

else

return 0;

int pop()

if(isEmpty())

printf(“Stack is Empty\n”);

exit(1);
}

return(stack[top--]);

Evaluation postfix expression


#include<stdio.h>

#include<string.h>

//char stack

char stack[25];

int top = -1;

void push(char item) {

stack[++top] = item;

char pop() {

return stack[top--];

//returns precedence of operators

int precedence(char symbol) {

switch(symbol) {

case '+':

case '-':

return 2;

break;

case '*':

case '/':

return 3;

break;

case '^':
return 4;

break;

case '(':

case ')':

case '#':

return 1;

break;

//check whether the symbol is operator?

int isOperator(char symbol) {

switch(symbol) {

case '+':

case '-':

case '*':

case '/':

case '^':

case '(':

case ')':

return 1;

break;

default:

return 0;

}
//converts infix expression to postfix

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

int i,symbol,j = 0;

stack[++top] = '#';

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

symbol = infix[i];

if(isOperator(symbol) == 0) {

postfix[j] = symbol;

j++;

} else {

if(symbol == '(') {

push(symbol);

}else {

if(symbol == ')') {

while(stack[top] != '(') {

postfix[j] = pop();

j++;

pop();//pop out (.

} else {

if(precedence(symbol)>precedence(stack[top])) {

push(symbol);

}else {

while(precedence(symbol)<=precedence(stack[top])) {

postfix[j] = pop();

j++;
}

push(symbol);

while(stack[top] != '#') {

postfix[j] = pop();

j++;

postfix[j]='\0';//null terminate string.

//int stack

int stack_int[25];

int top_int = -1;

void push_int(int item) {

stack_int[++top_int] = item;

char pop_int() {

return stack_int[top_int--];

//evaluates postfix expression

int evaluate(char *postfix){

char ch;

int i = 0,operand1,operand2;
while( (ch = postfix[i++]) != '\0') {

if(isdigit(ch)) {

push_int(ch-'0'); // Push the operand

}else {

//Operator,pop two operands

operand2 = pop_int();

operand1 = pop_int();

switch(ch) {

case '+':

push_int(operand1+operand2);

break;

case '-':

push_int(operand1-operand2);

break;

case '*':

push_int(operand1*operand2);

break;

case '/':

push_int(operand1/operand2);

break;

return stack_int[top_int];

}
void main() {

char infix[25],postfix[25];

printf("Enter the infix expression: ");

scanf("%s",infix);

convert(infix,postfix);

printf("Infix expression is: %s\n" , infix);

printf("Postfix expression is: %s\n" , postfix);

printf("Evaluated expression is: %d\n" , evaluate(postfix));

Evaluating Prefix Expression


//evaluation of prefix expression
#include<stdio.h>
#include<conio.h>
#include<string.h>
int stk[10];
int top=-1;
void push(int);
int pop();
void main()
{
char prefix[10];
int len,val,i,opr1,opr2,res;
clrscr();
printf("Enter the prefix Expression :");
gets(prefix);
len=strlen(prefix);
for(i=len-1;i>=0;i--)
{
switch(get_type(prefix[i]))
{
case 0:
val=prefix[i]-'0';
push(val);
break;
case 1: opr1=pop();
opr2=pop();
switch(prefix[i])
{
case '+': res=opr1+opr2;
break;
case '-': res=opr1-opr2;
break;
case '*': res=opr1*opr2;
break;
case '/': res=opr1/opr2;
break;
}
push(res);
}
}
printf("Result is %d",stk[0]);
getch();
}
void push(int val)
{
stk[++top]=val;
}
int pop()
{
return(stk[top--]);
}
int get_type(char c)
{
if(c=='+'||c=='-'||c=='*'||c=='/')
return 1;
else
return 0;
}

C Program to implement Stack using Linked Lists

#include<stdio.h>

#include<conio.h>

#include<malloc.h>

struct stack{

int data;

struct stack *next;

}*top=NULL;
struct stack *push(struct stack *,int);

struct stack *display(struct stack *);

struct stack *pop(struct stack *);

int peek(struct stack *);

void main()

int val,option;

clrscr();

do{

printf("\n1.PUSH");

printf("\n2.POP");

printf("\n3.PEEK");

printf("\n4.Display");

printf("\n5.exit");

printf("Enter an option");

scanf("%d",&option);

switch(option)

case 1:

printf("Enter the value to pushed on to the stack");

scanf("%d",&val);

top=push(top,val);

break;

case 2:

top=pop(top);
break;

case 3:

val=peek(top);

if(val!=-1)

printf("the value on top of the stack is %d",val);

else

printf("stack is empty");

break;

case 4:

top=display(top);

break;

}while(option!=5);

getch();

struct stack *push(struct stack *top ,int val)

struct stack *ptr;

ptr=(struct stack *)malloc(sizeof(struct stack));

ptr->data=val;

if(top==NULL)

ptr->next=NULL;

top=ptr;

}
else{

ptr->next=top;

top=ptr;

return top;

struct stack *display(struct stack *top)

struct stack *ptr;

ptr=top;

if(top==NULL)

printf("Stack is empty");

else

while(ptr!=NULL)

printf("%d",ptr->data);

ptr=ptr->next;

}}

return top;
}

struct stack *pop(struct stack *top)

struct stack *ptr;

ptr=top;

if(top==NULL)

printf("stack underflow");

else{

top=top->next;

free(ptr);

return top;

int peek (struct stack *top)

if(top==NULL)

return -1;

else

return top->data;

You might also like