Digital Assignment 6
Digital Assignment 6
LAB ASSIGNMENT-1
Write a program to convert the given infix notation in to a postfix notation
Syntax:-
#include<stdio.h>
#include<ctype.h>
char stk[100];
int top=-1;
void push(char x)
{
stk[++top]=x;
}
char pop()
{
if(top==-1)
return-1;
else
return stk[top--];
}
int priority(char x)
{
if(x=='(')
return 0;
if(x=='+'||x=='-')
return 1;
if(x=='*'||x=='/')
return 2;
return 0;
}
int main(){
char exp[100];
char *e,x;
scanf("%s",exp);
e=exp;
while(*e!='\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e=='(')
push(*e);
else if(*e==')')
{
while((x=pop())!='(')
printf("%c",x);
}
else
{
while(priority(stk[top])>=priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top !=-1)
{
printf("%c",pop());
}return 0;
}
Output:-
Q.2
Syntax;-
#include<stdio.h>
#include<ctype.h>
int stack[13];
int top=-1;
void push(int x)
{
stack[++top]=x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[100];
char *e;
int n1,n2,n3,num,i=0,j,chk;;
fgets(exp, 100, stdin);
while(exp[i]!='\0')
{
chk=0;
if(exp[i]==' ')
{
j=i;
while(exp[j-1]!='\0')
{
exp[j]=exp[j+1];
j++;
}
chk=1;
}
if(chk==0)
i++;
}
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1=pop();
n2=pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("%d",pop());
return 0;
}
Output:-