Slip 16_2 : A postfix expression of the form ab+cd-*ab/ is to be evaluated after accepting the values of a, b, c and d. Formulate the problem and write a C program to solve the problem by using stack.

 Solution :
#include<stdio.h>
#include<string.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;
 }
}
void postfix_eval(char str[20])
{ int i,op1,op2,val;
 for(i=0;str[i]!='\0';i++)
 { switch(str[i])
 {
 case '+': op2=pop();
 op1=pop();
 push(op1+op2);
 break;
 case '-': op2=pop();
 op1=pop();
 push(op1-op2);
 break;
 case '*': op2=pop();
 op1=pop();
 push(op1*op2);
 break;
 case '/': op2=pop();
 op1=pop();
 push(op1/op2);
 break;
 default:printf("Enter value of %c ",str[i]);
 scanf("%d",&val);
 push(val);
 }
 }
 pr
intf("Ans =%d ",pop());
}
main()
{ char str[20];
 printf("Enter postfix string ");
 scanf("%s",str);
 postfix_eval(str);
}

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”.