Question

Please help write a code in C that asks to translate from an infix expression (e.g....

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

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The code is given as follows. Support of whitespace characters is also added.

Please Note: I didn't read the tree part. So Im now giving you the solution using expression tree

Using Expression Tree

Example Output

Enter the infix expression
a * (b + c)

Preorder traversal:

*a+bc

Code

// The code is given as follows. Support of whitespace characters is also added.

// Using Expression Tree

// Example output

// Enter the infix expression
// a * (b + c )

// *a+bc

// Best Regards
// Code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define maxsize 20

typedef struct node

{ char data;

struct node *left;

struct node *right;

}

btree;
      /*stack stores the operand nodes of the tree*/
btree *stack[maxsize];

int top;


struct mystack {
    int stack_top;
    unsigned size;
    int* array;
};

char *strreverse(char *str) {
   char *p1, *p2;
   if (! str || ! *str)
       return str;
   for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) {
       *p1 ^= *p2;
       *p2 ^= *p1;
       *p1 ^= *p2;
   }
   return str;
}

int isEmpty(struct mystack* mystack) {
    return mystack->stack_top == -1 ;
}
char stack_top(struct mystack* mystack) {
    return mystack->array[mystack->stack_top];
}

struct mystack* makemystack( unsigned size ) {
    struct mystack* mystack = (struct mystack*) malloc(sizeof(struct mystack));

    if (!mystack)
        return NULL;

    mystack->stack_top = -1;
    mystack->size = size;

    mystack->array = (int*) malloc(mystack->size * sizeof(int));

    if (!mystack->array)
        return NULL;
    return mystack;
}

char stack_pop(struct mystack* mystack) {
    if (!isEmpty(mystack))
        return mystack->array[mystack->stack_top--] ;
    return '$';
}

void RemoveSpaces(char* source)
{
char* i = source;
char* j = source;
while(*j != 0)
{
    *i = *j++;
    if(*i != ' ')
      i++;
}
*i = 0;
}

void stack_push(struct mystack* mystack, char op) {
    mystack->array[++mystack->stack_top] = op;
}

int isOperand(char ch) {
    return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}

int Prec(char ch)
{
    switch (ch) {
       case '+': case '-': return 1;
        case '*': case '/': return 2;
        case '^': return 3;
    }
    return -1;
}

int infixstack_topostfix(char* exp)
{
    int i, k;

    struct mystack* mystack = makemystack(strlen(exp));
    if(!mystack) // See if mystack was maked successfully
        return -1 ;

    for (i = 0, k = -1; exp[i]; ++i)
    {
        if (isOperand(exp[i]))
            exp[++k] = exp[i];
     
        else if (exp[i] == '(')
            stack_push(mystack, exp[i]);

        else if (exp[i] == ')')
        {
            while (!isEmpty(mystack) && stack_top(mystack) != '(')
                exp[++k] = stack_pop(mystack);
            if (!isEmpty(mystack) && stack_top(mystack) != '(')
                return -1; // invalid expression         
            else
                stack_pop(mystack);
        }
        else // an operator is encountered
        {
            while (!isEmpty(mystack) && Prec(exp[i]) <= Prec(stack_top(mystack)))
                exp[++k] = stack_pop(mystack);
            stack_push(mystack, exp[i]);
        }

    }

    // stack_pop all the operators from the mystack
    while (!isEmpty(mystack))
        exp[++k] = stack_pop(mystack );

    exp[++k] = '\0';
}

btree *root;
btree *create(char exp[80]);
void preorder(btree *root);

int main(int argc, char const *argv[])
{
char infix[100];
printf("Enter the infix expression\n");
fgets(infix, 100, stdin);

RemoveSpaces(infix);

infixstack_topostfix(infix);

top=-1;     /*Initialize the stack*/
root=create(infix);


printf("\n Preorder traversal: \n\n");
preorder(root);
print("\n");
return 0;
}


btree *create(char exp[]) {

btree *temp;
int pos;
char ch;


void push(btree*);
btree *pop();
pos=0;
ch=exp[pos];
while(ch!='\0') {
    /*create new node*/
   
    temp=((btree*)malloc(sizeof(btree)));
    temp->left=temp->right=NULL;
    temp->data=ch;
   
    if(isalpha(ch))
      push(temp);
   
    else if(ch=='+' ||ch=='-' || ch=='*' || ch=='/') {
      temp->right=pop();
      temp->left=pop();
      push(temp);
    }
    else
      printf("\n Invalid char Expression\n");
   
    pos++;
    ch=exp[pos];
   
}

temp=pop();
return(temp);

}

void push(btree *Node) {
if(top+1 >=maxsize)
    printf("Error:Stack is full\n");

top++;
stack[top]=Node;
}

btree* pop() {
btree *Node;
if(top==-1)
    printf("\nerror: stack is empty..\n");
Node =stack[top];
top--;
return(Node);
}


/* functions for tree traversal*/

void preorder(btree *root) {
btree *temp;
temp=root;
if(temp!=NULL) {
    printf("%c",temp->data);
    preorder(temp->left);
    preorder(temp->right);
}
}

Add a comment
Know the answer?
Add Answer to:
Please help write a code in C that asks to translate from an infix expression (e.g....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are...

    We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are written in-between the operands). In a computer’s language, however, it is preferred to have the operators on the right side of the operands, i.e. 5 2 +. For more complex expressions that include parenthesis and multiple operators, a compiler has to convert the expression into postfix first and then evaluate the resulting postfix. Write a program that takes an “infix” expression as input, uses...

  • C++ Stack Program Write a program that uses stacks to evaluate an arithmetic expression in infix...

    C++ Stack Program Write a program that uses stacks to evaluate an arithmetic expression in infix notation. The program should NOT convert the infix to postfix and then evaluate the postfix. The program takes as input a numeric expression in infix notation, such as 3+4*2, and outputs the result. 1a)   Operators are +, -, *, / 1b) Assume that the expression is formed correctly so that each operation has two arguments. 1c) The expression can have parenthesis, for example: 3*(4-2)+6...

  • You are to write a program name expressionTree.java that evaluates an infix expression entered by the...

    You are to write a program name expressionTree.java that evaluates an infix expression entered by the user. The expression may contain the following tokens: (1) Integer constants (a series of decimal digits). (2)   One alphabetic character - "x" (representing a value to be supplied later). (3)   Binary operators (+, -, *, / and % (modulo)). (4)   Parentheses          You will parse the input expression creating an expression tree with the tokens, then use the postOrder tree traversal algorithm to extract...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression...

    C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression convertor Stacks A stack is an abstract data type which uses a sequential container and limits access to that container to one end. You may enter or remove from the container, but only at one end. Using the Linked List data structure from your last homework assignment, implement a Stack of type string. The Stack should only have one data member: the Linked List....

  • Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression...

    Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression. Right now, it works with single digits. I need to modify it so that it can evaluate expressions with also 2 digits, example: (60+82)%72. Additionally I need to display an error when the parenthesis don't match like (89+8(. I have muted some line that would print the postfix expression with a space like: 22 8 + when the input...

  • I NEED SAMPLE PRINT OUT AS WELL AS CODE PLEASE!!!! Objectives: To gain experience with stacks....

    I NEED SAMPLE PRINT OUT AS WELL AS CODE PLEASE!!!! Objectives: To gain experience with stacks. Documentation: Explain the purpose of the program as detail as possible - 8%. Develop a solution for the problem and mention algorithms to be used -12% List data structures to be used in solution. - 5%. Give a description of how to use the program and expected input/output - 5% Explain the purpose of each class you develop in the program. - 5%. Programming:...

  • Q1) Write a method called inToTree of ExpressionTree class which takes a string of infix expression...

    Q1) Write a method called inToTree of ExpressionTree class which takes a string of infix expression (fully parenthesized), resets the root of the expression tree to such tree which constructed from the expression. The root set to null of the expression contains characters other than value, operator, and parenthesis or if it’s not an in-fix full parenthesized expression. You may assume each value is single digit only . public void inToTree(String expression){ You may use a JCF Deque class as...

  • In the following code I give, everytime it will output ")". Input : ((A+B)*((C-D)/(E^F))) Expected output...

    In the following code I give, everytime it will output ")". Input : ((A+B)*((C-D)/(E^F))) Expected output : ((A+B)*((C-D)/(E^F))) A+B*C-D/E^F my output : ) My code : class Et: def __init__(self , value): self.value = value self.left = None self.right = None def isOperator(c): if (c == '+' or c == '-' or c == '*' or c == '/' or c == '^' ): return True else: return False def inorder(t): if t is not None: inorder(t.left) print (t.value) inorder(t.right)...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT