Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Prefix Evaluation (unlike postfix described in class) has the evaluation strateg

ID: 3822274 • Letter: P

Question

Prefix Evaluation (unlike postfix described in class) has the evaluation strategy of [operation, data, data]. Whenever such a pattern is encountered, the operation is performed on the two data. For example +23 45 Indicates that we are performing the addition operation on the values 23 and 45 (result is 68). Write a pseudo code to obtain the result of a prefix expression using a queue. Your pseudo code should also determine when invalid prefix syntax has occurred. For the example above, the queue Q will look something like: Head rightarrow+ 23 45 You may also assume a operations given in question 1 are available to you in the queue ADT.

Explanation / Answer

int preEval(char buffer[])

    {

    int i, result, length, num1, num2;

    char opr, opr1, temp1, temp2, token[2], item;

    QUEUE q;

    initQueue(&q);

    for (i = 0; i < strlen(buffer); i++)

        {

        enQueue(&q, buffer[i]);

        }

       do

        {

        length = q.rear - q.front;

        if((!isdigit(q.data[q.front])) && (isdigit(q.data[q.front+1])) && (isdigit(q.data[q.front+2])))

          {

          deQueue(&q, &opr);

          deQueue(&q, &temp1);

          token[0] = temp1;

          token[1] = '';

          num1 = atoi(token);

          deQueue(&q, &temp2);

          token[0] = temp2;

          token[1] = '';

          num2 = atoi(token);

          if (opr == '+')

            result = num1 + num2;

          else if (opr == '-')

            result = num1 - num2;

          else if (opr == '*')

            result = num1 * num2;

          else if (opr == '/')

            result = num1 / num2;

          else if (opr == '%')

            result = num1 % num2;

            //printf("Result: %d ", result);

         result = result + '0';

          enQueue(&q, result);

          }

        else

          {

           deQueue(&q, &opr1);

           enQueue(&q, opr1);

          }

       }

       while(length > 1);

    //printf("num1: %d ", num1);

    //printf("num2: %d ", num2);

    while(deQueue(&q, &item))

         {

         printf("%c ", item);

         }

    return(0);

    }