Please help write a code in C that asks to translate from an infix expression (e
ID: 3724197 • Letter: P
Question
Please help write a code in C that asks to translate from an infix expression (e.g. a * (b + c ) ) to a prefix notation (i.e., *a+bc) . You may assume that all the variables are one char and that the operators are limited to +, - , *.
The infix expression is entered by the user from the command prompt. It has a maximum length of 20 characters and it must be correct – you do not need to check for correctness
Build a binary tree for the infix expression. Your application should handle parenthesis.
Develop a function to traverse the tree and print the equivalent prefix expression to the screen
Explanation / Answer
#include<stdio.h>
#include<string.h>
#include <ctype.h>
void push(char element); //pushing an element in the stack
char pop(); //poping out the element
int precedence(char element); //getting the precedence
char stack[100]; // Stack formation
int top=-1; //pointing the top of the element
void main()
{
char infix[50],prefix[50],c,element;
int i=0,k=0;
printf("intput the infix Expression");
scanf("%s",infix);
push('#'); //push # to the bottom of the stack to know the end of the expression
strrev(infix); //reversing the expression
while( (c=infix[i++]) != '')
{
if( c == ')')
push(c);
else
if(isalnum(c))
prefix[k++]=c;
else
if( c == '(')
{
while( stack[top] != ')')
prefix[k++]=pop();
element=pop();
}
else
{
while( precedence(stack[top]) >= precedence(c) )
prefix[k++]=pop();
push(c);
}
}
while( stack[top] != '#')
prefix[k++]=pop();
prefix[k]='';
strrev(prefix);
strrev(infix);
printf("Given Infix Expression: %s Prefix Expression: %s ",infix,prefix);
}
void push(char element)
{
stack[++top]=element;
}
char pop()
{
return(stack[top--]);
}
int precedence(char element)
{
switch(element)
{
case '#': return 0;
break;
case ')': return 1;
break;
case '+': break;
case '-': return 2;
break;
case '*': break;
case '/': return 3;
break;
}
}