Slip 9_1,Slip 25_2 : Write a program to convert an infix expression of the form (a*(b+c)*((da)/b)) into its equivalent postfix notation. Consider usual precedence’s of operators. Use stack library of stack of characters using static implementation.

 Solution :

Header File : stack.h

#include<stdio.h>

char s[20];

int top;

void init()

{

 top=-1;

}

int isempty()

{ if(top==-1)

 return 1;

 else return 0;

}

int isfull()

{ if(top==19)

 return 1;

 else

 return 0;

}

void push(char data)

{

 if(isfull()==1)

 printf("\nStack is full ");

 else

 { top++;

 s[top]=data;

 }

}

char pop()

{ char data;

 if(isempty()==1)

 printf("\nStack is empty ");

 else

 { data=s[top];

 top--;

 return data;

 }

}

int peek()

{ return s[top];

}

Program File :

#include<stdio.h>

#include "stack.h"

int priority(char ch)

{ switch(ch)

 {

 case '(':return 0;

 case '+':

 case '-':return 1;

 case '*':

 case '/':return 2;

 case '^':

 case '$':return 3;

 }

 return 0;

}

void convert(char str[20])

{

 int i,j=0;

 char post[20],ch,ch1;

 init();

 for(i=0;str[i]!='\0';i++)

 { ch=str[i];

 switch(ch)

 {

 case '(':push(ch);

 break;

 case '+':

 case '-':

 case '*':

 case '/':

 case '$':

 case '^':

 while(!isempty() && (priority(peek())>=priority(ch)))

 {

 post[j]= pop();

 j++;

 }

 push(ch);

 break;

 case ')':while((ch1=pop())!='(')

 { post[j]=ch1;

 j++;

 }

 break;

 default:post[j]=ch;

 j++;


 }

 }

 while(!isempty())

 { post[j]=pop();

 j++;

}

post[j]='\0';

 printf("\n Postfix string = %s ",post);

}

main()

{

 char infix[20];

 printf("\nEnter the infix expression ");

 scanf("%s",infix);

 convert(infix);

}




Comments

Popular posts from this blog

Slip 22_2: Read the data from file 'cities.txt' containing names of cities and their STD codes. Accept a name of the city from user and use sentinel linear search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”. Solution :

Slip10_2, 30_1 : Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using bubble sort or selection sort

Slip 23_2: Read the data from file ‘sortedcities.txt’ containing sorted names of cities and their STD codes. Accept a name of the city from user and use binary search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”.