Question

In: Computer Science

CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can...

CS 400 Assignment 4
Stack application: postfix expression evaluation.

Description:
- The stack data structure can be used to evaluate postfix expressions. Please refer to the first 14 pages of this tutorial for postfix expression evaluation: http://www.cs.nthu.edu.tw/~wkhon/ds/ds10/tutorial/tutorial2.pdf

Requirement:
- deal with single digit positive integers only. Operands and operators are fully separated by space. 
- learn and use STL stack: http://www.cplusplus.com/reference/stack/stack/
- learn and use isdigit(): http://www.cplusplus.com/reference/cctype/isdigit/  
- take in a postfix arithmetic expression from cin, and evaluate its value. 
- supported operators: +, -, *, /
- for invalid postfix expression, print out an error message and end the program. 
- output the evaluated value of valid expressions. 

Example1: 
- (valid expr) 4 3 - 5 * 
-- push 4 into stack 
-- push 3 into stack 
-- minus operator (-) detected: pop 3 out of stack, as operand_2
-- pop 4 out of stack, as operand_1
-- perform operand_1 minus operand_2, then push the result (1) into stack. 
-- push 5 into stack 
-- multiply operator (*) detected: pop 5 out of stack, as operand_2
-- pop 1 out of stack, as operand_1
-- perform operand_1 times operand_2, then push the result (5) into stack. 
-- input done. check stack value... output final answer: 5

Example2: 
- (invalid expr) 4 4 3 - 5 * is invalid since the stack will have two numbers inside it. 
- (invalid expr) 4 5 5 - / is invalid due to the divide-by-zero error. 

Grading:
- compilable and meaningful attemps: 20 points. 
- correct usage of STL stack: 20 points, including object creation, push(), top() and pop().
- correct postfix expression evaluation: 30 points.
- error handling: 20 points, including divide-by-zero error and invalid expression error
- comments, file_name and indentation: 10 points. 

File_name: 
postfix_eval.cpp

Solutions

Expert Solution

// C++ program to evaluate postfix expression consisting of single digit positive integer and

// operators and operands are fully separated by space

#include <iostream>

#include <stack>

#include <cctype>

using namespace std;

int main() {

       string postfix_exp;

       stack<int> st;

       cout<<"Program to evaluate postfix expression(consisting of single digit positive integers only and Operands and operators are fully separated by space. ) "<<endl;

       // input of postfix expression

       cout<<"Enter the postfix expression : ";

       getline(cin,postfix_exp);

       postfix_exp = postfix_exp.substr(0,postfix_exp.length()-1); // remove '\n' from end

       // loop over the expression

       for(unsigned int i=0;i<postfix_exp.length();i++)

       {

             // check if the character is a digit, then push the int to the stack

             if(isdigit(postfix_exp[i]))

                    st.push((int)(postfix_exp[i]-'0')); // convert the char to int and push it to stack

             else if(!isspace(postfix_exp[i])) // if the character is not a space

             {

                    int n1, n2;

                    // check if stack is empty, then print error and exit

                    if(st.empty())

                    {

                           cout<<"ERROR: Invalid expression "<<endl;

                           return 1;

                    }

                    // if stack is not empty, remove and assign the top element to n2

                    n2 = st.top();

                    st.pop();

                    // check if stack is empty, then print error and exit

                    if(st.empty())

                    {

                           cout<<"ERROR: Invalid expression "<<endl;

                           return 1;

                    }

                    // if stack is not empty, remove and assign the top element to n1

                    n1 = st.top();

                    st.pop();

                    // check the operator

                    if(postfix_exp[i] == '+') // addition

                           st.push(n1+n2); // perform addition and push the result back to stack

                    else if(postfix_exp[i] == '-') // subtraction

                           st.push(n1-n2); // perform n1-n2 and push the result back to stack

                    else if(postfix_exp[i] == '*') // multiplication

                           st.push(n1*n2); // perform multiplication and push the result back to stack

                    else if(postfix_exp[i] == '/') // division

                    {

                           // check if n2 is not zero, then perform n1/n2 and push the result back to stack

                           if(n2 != 0)

                                 st.push(n1/n2);

                           else // if n2 is 0, print error and exit

                           {

                                 cout<<"ERROR: division by zero "<<endl;

                                 return 1;

                           }

                    }else // if any other character found, print error and exit

                    {

                           cout<<"ERROR: Invalid operator "<<endl;

                           return 1;

                    }

             }

       }

       // if stack is empty after scanning the entire expression, print error and exit

       if(st.empty())

             cout<<"ERROR: Invalid expression "<<endl;

       else{

             // get the result from top of stack

             int result = st.top();

             st.pop(); // remove the result from top

             // if stack is non-empty after getting the result, print error and exit else print result

             if(st.empty())

                    cout<<"Result : "<<result<<endl;

             else

                    cout<<"ERROR: Invalid expression "<<endl;

       }

       return 0;

}

//end of program

Output:


Related Solutions

CS 209 Data Structure (Postfix notation) Postfix notation is a way of writing expressions without using...
CS 209 Data Structure (Postfix notation) Postfix notation is a way of writing expressions without using parentheses. For example, the expression (1 + 2) * 3 would be written as 1 2 + 3 *. A postfix expression is evaluated using a stack. Scan a postfix expression from left to right. A variable or constant is pushed into the stack. When an operator is encountered, apply the operator with the top two operands in the stack and replace the two...
Write the code for postfix expression in C++ using a linked stack that can take numbers...
Write the code for postfix expression in C++ using a linked stack that can take numbers bigger than 9 (any size the user gives) and pushes the final result onto the top of the stack
Postfix Evaluation (JAVA PROGRAMMING) Write class PostfixEva1uator that evaluates a postfix expression such as 6 2...
Postfix Evaluation (JAVA PROGRAMMING) Write class PostfixEva1uator that evaluates a postfix expression such as 6 2 + 5 * 8 4 / - The program should read a postfix expression consisting of single digits and operators into a StringBuilder, The program should read the expression and evaluate it (assume it's valid). The algorithm to evaluate a postfix expression is shown below. Use +, -, *, /, and ^. ^ is the exponent. Append a right parenthesis ') ' to the...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
For this assignment you will write a class that transforms a Postfix expression (interpreted as a...
For this assignment you will write a class that transforms a Postfix expression (interpreted as a sequence of method calls) into an expression tree, and provides methods that process the tree in different ways. We will test this using our own program that instantiates your class and calls the expected methods. Do not use another class besides the tester and the ExpressionTree class. All work must be done in the class ExpressionTree. Your class must be called ExpressionTree and have...
Using STL stack class, implement in C++ a function that converts an infix expression to postfix...
Using STL stack class, implement in C++ a function that converts an infix expression to postfix expression,
Find is the final result of evaluating the following postfix expression using a stack. Show each...
Find is the final result of evaluating the following postfix expression using a stack. Show each push and pop operation. 85 5 / 4 * 5   6 +   10    5 -   * +
Your assignment for this program is to evaluate a numeric expression in postfix notation using a...
Your assignment for this program is to evaluate a numeric expression in postfix notation using a dynamic (pointer based) stack. As stated in the handout, in order to evaluate a numeric expression, a compiler converts an infix numeric expression to postfix notation and then it uses an algorithm and a stack to evaluate the expression. Your program should implement the pseudocode algorithm described in the attached handout. Your program will read and evaluate expressions stored in an input file (infile.txt)....
Assignment #2 (JAVA) In assignment 1 you had used the data structure called Stack to evaluate...
Assignment #2 (JAVA) In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by first converting the given infixed expressions to postfixed expressions, and then evaluated the post fixed expression. Repeat the exercise for this assignment (assignment 2) by using the data structure called Binary Trees. Your output must display the original expression, the postfixed expression representing the Binary tree, and the evaluated result. Please bear in mind that a given expression could result in...
CS 400 Assignment 2: applying ArrayList In this assignment, you are going to build a program...
CS 400 Assignment 2: applying ArrayList In this assignment, you are going to build a program that can help rental car companies to manage their rental fleet. Requirement: - build ArrayList class as container. - build Car class/structure to represent car objects. - An ArrayList object is to hold Car objects. Car class should have following fields: - id (int) - make (string) - model (string) - color (string) Instructions: - make up 15 cars and save them into a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT