Question

Using ADT Stack: Evaluating infix expressions by converting them to postfix expressions Postfix notation: In a...

Using ADT Stack: Evaluating infix expressions by converting them to postfix expressions Postfix notation: In a postfix expression, a binary operation follows its two opperands. The order of the operands in a infix expression is the same as in the corresponding postfix expression but the order of the operators might change based on the precedence of the operators and the existing of paranthses. Infix Postfix a + b a b + (a + b) * c a b + c * a + b * c a b c * +

1. Infix-to-postfix convertion To convert an infix to postfix expression we can use a stack to store temporary operators and open and close parantheses. Take the following actions which depend on the currently processed symbol from the infix expression (scanned from left to right). Construct the output (resulting) expression, by appending to its end the correct items (operands or operators). If Operand: Append the operand to the end of the output expression. If Operator ^: Push it onto the stack. If Operator +, -, *, /: - If the stack is empty or its top entry is an operator that has a lower precedence than the new operator, push the new operator onto the stack (Note: ‘*’ and ‘/’ have higher precedence than ‘+’ and ‘-‘.) - Otherwise pop operators from the stack and append them to the output expression until the stack is empty, or its top entry has a lower precedence than the new operator. Then push the new operator onto the stack. If Open paranthesis: Push ( onto the stack. If Close paranthesis: Pop operators from the stack and append them to the output expression until an open paranthesis is poped. Then discard both parantheses.

Problem 1 ) Convert the following infix expressions to postfix expressions using the rules given above: (a – b * c ) / (d * e + (d – c))

2.Evaluating postfix expressions To evaluate a postfix expression: scan the expression and take the following actions depending on the currently processed symbol: If Operand: push it onto the stack If Operator: - pop an operand from the stack (this will be the second operand, which has been pushed last); - pop another operand from the stack (this will be the first operand) - perform the operation and push the result back onto the stack.

Problem 2) Using the rules given above, evaluate the following postfix expression, if a = 2, b = 3, c = 4, d = 5: a b c - / d *

The language is Java

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

================ code for InfixToPostfix ================================java used============

import java.util.Stack;

class InfixToPostFix
{
////////////////////////////////////////////////
   // calculating precedence order
   static int PrecedenceOrder(char ch)
   {
       switch (ch)
       {
       case '+':
       case '-':
           return 1;
  
       case '*':
       case '/':
           return 2;
  
       case '^':
           return 3;
       }
       return -1;
   }
////////////////////////////////////////////////////  
   // Method that converts infix to postfix expression
   static String myInToPostfix(String exp)
   {
      
       String result = new String("");
      
       // a empty stack
       Stack<Character> stack = new Stack<>();
      
       for (int i = 0; i<exp.length(); ++i)
       {
           char c = exp.charAt(i);
          
           // scanning character is lettre or digit
           if (Character.isLetterOrDigit(c))
               result += c;
          
           // character is an '(' do it
           else if (c == '(')
               stack.push(c);
          
           // character is ) loop until ( found
           else if (c == ')')
           {
               while (!stack.isEmpty() && stack.peek() != '(')
                   result += stack.pop();
              
               if (!stack.isEmpty() && stack.peek() != '(')
                   return "Expression is not valid---";                  
               else
                   stack.pop();
           }
           else // operator found
           {
               while (!stack.isEmpty() && PrecedenceOrder(c) <= PrecedenceOrder(stack.peek())){
                   if(stack.peek() == '(')
                       return "Expression is not valid--";
                   result += stack.pop();
           }
               stack.push(c);
           }
  
       }
  
       // poping the operators
       while (!stack.isEmpty()){
           if(stack.peek() == '(')
               return "Expression is invalid----";
           result += stack.pop();
       }
       return result;
   }
   ////////////////////////////////////////////////////
     
   public static void main(String[] args)
   {
       String exp = "a+b*(c^d-e)^(f+g*h)-i";
       System.out.println(myInToPostfix(exp));
exp = "a + b a b + (a + b) * c a b + c * a + b * c a b c * +";
System.out.println(myInToPostfix(exp));
   }
}


----------------------------------------------------------------------------------------------------------------------------------------------------

Screenshots of the code and the output are:

-----------------------------------------------------------------------------------------------------------------------------------------------------

================================= end ====================================================

**************************** Please like the post if you liked it *******************************************************************

Add a comment
Know the answer?
Add Answer to:
Using ADT Stack: Evaluating infix expressions by converting them to postfix expressions Postfix notation: In a...
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
  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • By using PYTHON language Postfix to Infix using Stack Develop a stack application that can convert...

    By using PYTHON language Postfix to Infix using Stack Develop a stack application that can convert Postfix notation to Infix notation using the following algorithm. In your stack application, you can use only two stacks, one for a stack that can store Postfix notation, and the other is a stack to store infix notation. Also, it would help if you had a function to distinguish between an operation or an operand. Input A B C * + D E /...

  • Code should be written in java Write a program to convert an infix expression to postfix...

    Code should be written in java Write a program to convert an infix expression to postfix expression using stack. Algorithm: a) Create a stack b) For each character t in the input stream If(t is an operand) append t to the output. Else if (t is a right parenthesis) Pop and append to the output until a left parenthesis is popped (but do not append this parenthesis to the output). Else if(t is an operator or left parenthesis) Pop and...

  • Given the following C code. Develop a evaluate post fix function that calculates the converted post...

    Given the following C code. Develop a evaluate post fix function that calculates the converted post fix. #include <stdio.h> #include <ctype.h> #define max 10 char s[100]; int top=-1; void push(char); char pop(); int precede(char); main(){    char infix[100],postfix[100],ch;    int i=0,j=0;    // Read infix expression from user    printf("Enter infix expression:");    scanf("%s",infix);    // evaluate each char in infix expression    while((ch=infix[i++])!='\0'){        // if it is number, add it to postfix expression        if(isalnum(ch)){   ...

  • In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack...

    In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack are of generic DataType. This means use should use templating and your Node class. Structure  The stack data items are linearly ordered from the most recently added (the top) to the least recently added (the bottom). This is a LIFO scheme. Data items are inserted onto (pushed) and removed from (popped) the top of the stack.  Operations  Constructor. Creates an empty stack.  Copy constructor....

  • EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation;...

    EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation; in it, operators are written between their operands: X + Y. Such expressions can be ambiguous; do we add or multiply first in the expression 5 + 3 * 2? Parentheses and rules of precedence and association clarify such ambiguities: multiplication and division take precedence over addition and subtraction, and operators associate from left to right. This project implements and exercises a stack-based algorithm that evaluates...

  • 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...

  • a) Show the steps that a stack uses to convert the algebraic expression a*(b+c/d from infix to postfix notation. Indicate each intermediate change in the stack and postfix output. (Be sure to...

    a) Show the steps that a stack uses to convert the algebraic expression a*(b+c/d from infix to postfix notation. Indicate each intermediate change in the stack and postfix output. (Be sure to identify how operator precedence is determined. b) show the steps a stack uses to evaluate the postfix expression from part (a) when (a-6, b-4, c-2, d 5) c) Show the steps a stack uses to produce an expression tree with the postfix expression from part (a). a) Show...

  • Python Issue Postfix notation (also known as Reverse Polish Notation or RPN in short) is a...

    Python Issue Postfix notation (also known as Reverse Polish Notation or RPN in short) is a mathematical notation in which operators follow all of its operands. It is different from infix notation in which operators are placed between its operands. The algorithm to evaluate any postfix expression is based on stack and is pretty simple: Initialize empty stack For every token in the postfix expression (scanned from left to right): If the token is an operand (number), push it on...

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