Batch - B Practical Test Question

Batch - B Practical Test Question
Batch - B Practical Test Question

INFIX to POSTFIX with Evaluation

//Infix to Postfix Conversion
#include<stdio.h>
int getPriority(char);
int isAplhaNum(char);
void push(char);

char pop();
char infix[100];
char postfix[100];
char prefix[100];
char stack[20];

int stackN[20];
void pushN(int);
int popN();
int doOperation(int ,int ,char );
int tosN=0;

int tos=-1;
int main()
{
int is=0,ip=0;
int op1,op2,val=0;
push('(');
printf("\n Enter String : ");
scanf("%s",infix);
//printf("\n Tracing of Infix to Postfix Process \n");
//printf("\n %9s | %15s | %15s |\n","INPUT","STACK","POSTFIX");
while(infix[is]!='\0')
{
if(isAplhaNum(infix[is]) || infix[is]=='(')
{

if(infix[is]=='(')
{
push(infix[is]);
//postfix[ip++]=infix[is];
}
else
{
postfix[ip++]=infix[is];
}
}
else
{
if(infix[is]==')')
{
while(stack[tos]!='(')
{
postfix[ip++]=pop();
}

pop();
}
else if(stack[tos]!='(')
{
while(getPriority(stack[tos]) >= getPriority(infix[is]))
{
postfix[ip++]=pop();
}
push(infix[is]);

}
else
{
push(infix[is]);
}
}
push('\0');
postfix[ip++]='\0';
//printf("\n\t%c  | %15s | %15s |",infix[is],stack,postfix);
ip--;
pop();

is++;

}
while(stack[tos]!='(')
{
postfix[ip++]=pop();
}
postfix[ip++]='\0';
//printf("\n\t%c  | %15s | %15s |",infix[is],stack,postfix);

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

//Logic of PostFix to Evalaution Starts from Here
ip=0;
while(postfix[ip]!='\0')
{
if(isAplhaNum(postfix[ip]))
{
pushN(postfix[ip++]-48);
}
else
{
op1=popN();
op2=popN();
val=doOperation(op1,op2,postfix[ip++]);
pushN(val);
}
}
printf("\n Evaluation Process Answer = %d",popN());
return 0;
}

int getPriority(char ch)
{
switch(ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
int isAplhaNum(char ch)
{
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z') || (ch>='0' && ch<='9'))
{
return 1;
}
else
{
return 0;
}
}
void push(char c)
{
stack[++tos]=c;
}
char pop()
{
return stack[tos--];
}

//Functions will be used in POSTFIX to EVALUATION
void pushN(int c)
{
stackN[++tosN]=c;
}
int popN()
{
return stackN[tosN--];
}
int doOperation(int a,int b,char c)
{
int ans=1;
switch(c)
{
case '+':
return b+a;
case '/':
return b/a;
case '*':
return b*a;
case '-':
return b-a;
case '^':
while(a>0)
{
ans=ans*b;
a = a - 1;
}
return ans;
}
}

Comments