If Screen is half, please rotate the Mobile then it is full program available
4. Design, Develop and Implement a Program in C for converting an Infix Expression to Postfix Expression. Program should support for both parenthesized and free parenthesized expressions with the operators: +, -, *, /, %(Remainder), ^(Power) and alphanumeric operands.
#include <stdio.h>
#include <stdlib.h>
typedef enum {lparen, rparen, plus, minus, times, divide, mod, pow, eos, operand} PRECEDENCE;
PRECEDENCE stack[100];
int top = 0;
char infix[100];
/* isp and icp arrays -- index is value of precedence
lparen, rparen, plus, minus, times, divide, mod, pow, eos */
int isp[] = {0, 19, 12, 12, 13, 13, 13, 14, 0};
int icp[] = {20, 19, 12, 12, 13, 13, 13, 14, 0};
void getInfix ( void )
{
printf ( "\n\nEnter the valid Infix expression\n\n" );
gets ( infix );
}
void push ( PRECEDENCE symbol )
{
/* add an item to the global stack */
stack[++ top] = symbol;
}
PRECEDENCE pop ( void )
{
/* delete and return the top element from the stack */
return stack[top --];
}
PRECEDENCE getToken ( char *symbol, int *n )
{
*symbol = infix[(*n)++];
switch ( *symbol )
{
case '(' : return lparen;
case ')' : return rparen;
case '+' : return plus;
case '-' : return minus;
case '/' : return divide;
case '*' : return times;
case '%' : return mod;
case '^' : return pow;
case '\0': return eos;
case ' ' : return eos;
/* no error checking, default is operand */
default : return operand;
}
}
void printToken ( PRECEDENCE symbol )
{
switch ( symbol )
{
case plus : putchar ( '+' ); break;
case minus : putchar ( '-' ); break;
case divide : putchar ( '/' ); break;
case times : putchar ( '*' ); break;
case mod : putchar ( '%' ); break;
case pow : putchar ( '^' );
}
}
void postfix ( void )
{
char symbol;
PRECEDENCE token;
int n = 0;
stack[0] = eos;
printf ( "\n\n Equivalent Postfix expression\n\n" );
token = getToken ( &symbol, &n );
while ( token != eos )
{
if ( token == operand )
{
putchar ( symbol );
}
else if ( token == rparen )
{
/* unstack tokens until left parenthesis */
while ( stack[top] != lparen )
{
printToken ( pop ( ) );
}
pop ( ); /* discard the left parenthesis */
}
else
{
/* remove and print symbols whose isp is greater
than or equal to the current token's icp */
while ( isp[stack[top]] >= icp[token] )
{
printToken ( pop ( ) );
}
push ( token );
}
token = getToken ( &symbol, &n );
} //while ends
while ( ( token = pop ( ) ) != eos )
{
printToken ( token );
}
putchar ( '\n' );
}
int main ( void )
{
printf ( "\n\nINFIX TO POSTFIX Demonstration\n\n" );
getInfix ( );
postfix ( );
fflush ( stdin );
getchar();
return 0;
}
/*
OUTPUT:-
INFIX TO POSTFIX Demonstration
Enter the valid Infix expression
((a*b)+(c/d))
Equivalent Postfix expression
ab*cd/+
INFIX TO POSTFIX Demonstration
Enter the valid Infix expression
(A+B)*D+E/(F+A*D)+C
Equivalent Postfix expression
AB+D*EFAD*+/+C+
*/