Question

For this assignment, you are to write a program, which will calculate the results of Reverse...

For this assignment, you are to write a program, which will calculate the results of Reverse Polish expressions that are provided by the user.

You must use a linked list to maintain the stack for this program.

You must handle the following situations (errors):
Too many operators (+ - / *)
Too many operands (doubles)
Division by zero

The program will take in a Polish expression that separates the operators and operands by a single space, and terminates the expression with an equals sign.

The program will continue to take and evaluate expressions until the user enters a zero (0) on a line by itself followed by a new line.

Your sample output should show the handling of all the error conditions as well as make use of all of the operators.

Sample IO: (note: formatting of output isn’t a critical issue but proper input processing is essential)
Input Output
10 15 + = 25
10 15 - = -5
2.5 3.5 + = 6 (or 6.0)
10 0 / = Error: Division by zero
10 20 * / = Error: Too many operators
12 20 30 / = Error: Too many operands
-10 -30 - = 20
100 10 50 25 / * - -2 / = -40

NO ARRAYS

NO LIBRARIES (just <iostream>)

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

#include<iostream>
#include<sstream>
using namespace std;

struct node
{
   double data;
   struct node *next;
};

class Stack
{
   private:
       struct node *top;
       double size;
   public:
       Stack()
       {
           top=NULL;
           size=0;
       }
       void push(double val);
       bool pop();
       bool isEmpty();
       double topOfStack();
       double sizeOfStack();
};

void Stack::push(double val)
{
   //Increment size by 1
   size++;

   //create new Node
   struct node *newNode=new node;
   newNode->data=val;
   newNode->next=NULL;

   //Append to front of list
   newNode->next=top;
   top=newNode;
}

bool Stack::pop()
{
   //If stack empty
   if(isEmpty())
   {
       return false;
   }
   //Decrement size by 1
   size--;
   //Delete top
   struct node *temp=top;
   top=top->next;
   free(temp);
   return true;
}

bool Stack::isEmpty()
{
   return top==NULL;
}

double Stack::topOfStack()
{
   //If stack is not empty
   if(!isEmpty())
   {
       return top->data;
   }
   return -9999;
}

double Stack::sizeOfStack()
{
   return size;
}

bool evaluateExpression(string expr, double *result)
{
   Stack s;
   double x,y;
   string word;
   // to split the strng with respect to white spaces
   istringstream ss(expr);
   do
   {
       //store each word
       ss >> word;
       //If word is = then stop
       if(word=="=")
       {
           break;
       }

       //If operatos
       if(word=="+" || word=="-" || word=="*" || word=="/")
       {
           if(s.isEmpty())
           {
               cout<<"Error: Too many operators"<<endl;
               return false;
           }
            y=s.topOfStack();
            s.pop();
            if(s.isEmpty())
           {
               cout<<"Error: Too many operators"<<endl;
               return false;
           }
            x=s.topOfStack();
            s.pop();
            switch(word[0])
            {
                case '+':
                       s.push(x+y);
                       break;
                case '-':
                       s.push(x-y);
                       break;
                case '*':
                       s.push(x*y);
                       break;
                case '/':
                       if(y==0)
                       {
                           cout<<"Error: Division by zero"<<endl;
                           return false;
                       }
                       s.push(x/y);
                       break;
            }  
       }
       else
       {
           //stod() is to convert string to double
           s.push(stod(word));
       }
    }while(ss);
  
    //If more operands left
    if(s.sizeOfStack()>1)
    {
       cout<<"Error: Too many operands"<<endl;
       return false;
    }
    //Store top of stack into result variable
    *result=s.topOfStack();
    return true;
}

int main()
{
   Stack s;
   string expr;
   double result=0;
   while(true)
   {
       getline(cin,expr);
       //If user enters zero then break the loop
       if(expr=="zero")
       {
           break;
       }
       cout<<expr<<" ";
       //If expression is valid then print output
       //value of expresion stores in result since we passed address of result
       if(evaluateExpression(expr,&result))
       {
           cout<<result<<endl;
       }
   }
   return 0;
}

output screenshot:

C:\Users\srini\Desktop>g++ postfixEvaluation.cpp C:\Users\srini Desktop>a.exe 10 15 + = 110 15 + = 25 10 15 - = 110 15 - = 2.

Add a comment
Know the answer?
Add Answer to:
For this assignment, you are to write a program, which will calculate the results of Reverse...
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
  • You are to write a program that implements a Reverse Polish Notation Calculator in C using...

    You are to write a program that implements a Reverse Polish Notation Calculator in C using BISON and FLEX, You only have to edit the BISON and FLEX files. Link to the files to start and have a general view of the program: https://www.dropbox.com/sh/83yzs66jhftqj5b/AABZcY9Qwl84JdUFnYpQaZk9a?dl=0 Reverse Polish Notation is a mathematical notation in which every operator follows all of its operands. It is sometimes called postfix notation, and does not require any parentheses as long as each operator has a fixed...

  • Question: Write a Java program for Evaluating Postfix Expression 1. Input a postfix expression from user....

    Question: Write a Java program for Evaluating Postfix Expression 1. Input a postfix expression from user. 2. Evaluate expression using double stack made of your own linked list. 3. Show the result of expression or error if incorrect. Evaluating Postfix Expression Input an expression: 2 10 + 9 6 - / Evaluating Postfix Expression Input an expression: 20 10 + 9 6 - 1 Evaluating Postfix Expression Input an expression: 2 10 + 9 - / Result = 4.0 Result...

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

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

  • Total point: 15 Introduction: For this assignment you have to write a c program that will...

    Total point: 15 Introduction: For this assignment you have to write a c program that will take an infix expression as input and display the postfix expression of the input. After converting the postfix expression, the program should evaluate the expression from the postfix and display the result. What should you submit? Write all the code in a single file and upload the .c file. Problem We as humans write math expression in infix notation, e.g. 5 + 2 (the...

  • write a C program that evaluate algebraic expressions over real numbers in Reverse Polish Notation (RPN)

    Your program must evaluate algebraic expressions over real numbers in Reverse Polish Notation (RPN). + (addition), - (subtraction), * (multiplication) and / (division) should be treated as arithmetic operations. Depending on the selection, numerical values must be entered and displayed in decimal, hexadecimal or binary form. Example: The expression ((3+4) *(7+1.6-12) -5) / (3-8.7)Will be calculated on your RPN calculator as 3 4 + 7 1.6 + 12 - * 5 - 3 8.7 - / Your RPN computer's user...

  • Write an assembler program that asks the user (as shown below) for two integers and a...

    Write an assembler program that asks the user (as shown below) for two integers and a single character representing the arithmetic operations: addition, subtraction, multiplication and integer division (displays both quotient and remainder). Perform the requested operation on the operands and display the result as specified below. Assume SIGNED NUMBERS. The program should not divide by 0! If the user attempts to divide by 0, display the error message: "Cannot divide by zero." If this error occurs, the program should...

  • PLEASE HELP ASAP Write a 8088 assembly language program to accept input expressions from standard input...

    PLEASE HELP ASAP Write a 8088 assembly language program to accept input expressions from standard input consisting of an integer, an operator, and another integer and output the value of the expression to standard output. Valid operators are +, -, x and/ for addition, subtraction, multiplication and division respectively.

  • Write a MIPS math quiz program in MARS. The program should start with a friendly user...

    Write a MIPS math quiz program in MARS. The program should start with a friendly user greeting. From there, it should generate a random arithmetic problem. Your program will need to generate three random things: the first and second operand and the operator to use. Your program should generate random positive integers no greater than 20 for the operands. The possible operators are +, -, * and / (division). The user should be prompted for an answer to the problem....

  • In C++, write a program that reads a postfix expression from an input file. Then, the...

    In C++, write a program that reads a postfix expression from an input file. Then, the program should evaluate the postfix format and display the results. Use these concepts for the program: 1) Struct Node 2) Enqueue and Dequeue 3) Push and Pop 4) DO NOT USE classes 5) Possibly Stack Precondition: The expression will be read from a file (input.txt) that contains a single line. There will be no spaces between the operands and the operators. The following operators...

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