Batch - B Practical Test Question

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

Infix to Postfix Conversion using Stack

//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 stack[20];
int tos=-1;

int main()
{
int is=0,ip=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();
}
//postfix[ip++]=infix[is];
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 Final Output \n");
printf("\n Postfix = %s",postfix);
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--];
}

Comments