0% found this document useful (0 votes)
4 views

Assignment 5

Uploaded by

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

Assignment 5

Uploaded by

Naman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Data Structures in C

ASSIGNMENT-5

Name: Naman Kumar

Course: BTECH(CSE)

Section: B1

Class Roll No.: 45

University Roll No.: 2319143


Question: Infix to postfix conversion of
mathematical expression
Algorithm
Step1. Initialize a string ‘s’ containing
mathematical expression
Step2. Initialize a loop up to length of s
Step3. Check if incoming char is operand than
show it in resultant string ‘ans’
Step4. If incoming char is an operand
• If stack is empty, push onto stack st
• if stack is not empty, then
Check the precedence of top of stack and
incoming char
If incoming char is strong then push in to st
• If incoming character is weak or of same
precedence, then pop stack until the
condition is true or stack became empty
Step5. If string is finished, then output everything
from stack
#include<stdio.h>
#include<string.h>
void push(int st[],int ch,int *top)
{
st[++(*top)]=ch;
}
void pop(int st[],int *top)
{
(*top)--;
}
int isEmpty(int top)
{
if(top==-1)
{
return 1;
}
else
{
return 0;
}
}
int prec(char c)
{
switch(c)
{
case '+':return 1;
case '-':return -1;
case '*':return 2;
case '/':return -2;
default: return 0;

}
}
char oper(int a)
{
switch(a)
{
case 1:return '+';
case -1:return '-';
case 2:return '*';
case -2:return '/';
}

}
int main()
{
int st[100];
char s[100];
char ans[100];
int i,n,top=-1;
int a=0;
printf("ENTER THE EXPRESSION-");
scanf("%s",s);
n=strlen(s);
for(int i=0;i<n;i++)
{
if(s[i]=='(')
{
push(st,0,&top);
}
else if(s[i]==')')
{
while((st[top]!=0)&&(!isEmpty(top))){
int t=st[top];
pop(st,&top);
ans[a++]=oper(t);
}
pop(st,&top);
}
else if(s[i]>='a' && s[i]<='z')
{
ans[a++]=s[i];
}
else{
while(!isEmpty(top)&& (prec(s[i]))<=(prec(st[top])))
{
int t=st[top];
pop(st,&top);
ans[a++]=oper(t);
}
push(st,prec(s[i]),&top);
}
}
while(!isEmpty(top))
{
int t=st[top];
pop(st,&top);
ans[a++]=oper(t);
}
ans[a]='\0';

printf("%s",ans);
return 0;

You might also like