Question

In: Computer Science

IF YOU HAVE ANSWERED THIS QUESTION BEFORE THEN PLEASE DONOT ANSWER AGAIN. Your task for this...

IF YOU HAVE ANSWERED THIS QUESTION BEFORE THEN PLEASE DONOT ANSWER AGAIN.

Your task for this assignment is to implement a stack data structure in C++. This may be accomplished by utilizing the C++ standard template library (STL) or by utilizing a user-defined class.

  1. Implement a transaction-based stack data structure using C++. The program will be interactive. Data transactions will be entered at the command line and results will be displayed on the console.

  2. Each input transaction will contain an arithmetic expression in post-fix format. Assume that operands and operations are separated by a space on an input line that contains one arithmetic expression. An operand will be a positive or negative float number. An operation may be +, -, * or /. You may assume that each arithmetic expression is correctly formatted. However, your program should not allow an attempt to divide by zero. Instead of dividing by zero, your program should display an error message and then begin evaluating a new input transaction.

    Sample input transactions are these:

    1. 2.0 3.3 + (result = 5.3)

    2. 34*-2.5/ (result=-4.8)

    3. 9.5 8 3.0 2 * 6 - / + (result= “error: division by zero”)

  3. An input transaction containing “end-of-file” indicates there are no more transactions to be processed. Implement a stack to evaluate each expression and display the result. Use the C++ built-in class or a user-defined class to implement stack functions.

  4. The program will be run at the command prompt by navigating to the directory containing the executable version of the program after the program is compiled. The program should display a prompt requesting input, such as “Please enter an expression in post-fix notation:”.

5. You are encouraged to add additional comments throughout the program that your feel might be helpful to the reader of your source code.

Solutions

Expert Solution

#include <bits/stdc++.h>
#include <stack>
using namespace std;
  
int main()
{ 
    string S, T; 
    cout<<"Please enter an expression in post-fix notation:";
    //to create a stack to hold input strings
    stack<string> st; 
    //to input the entire string
    getline(cin, S); 
    //to split the given string by the delimeter space ' '
    stringstream X(S); 
    
    while (getline(X, T, ' ')) { 
        //if T is any operator
        if(T=="+" || T=="-"|| T=="*"|| T=="/"){
            //here first we need to convert the string to float using stof()
            float val1=stof(st.top());
            st.pop();
            float val2=stof(st.top());
            st.pop();
            //to check for division by zero error
            if(val1==0.0 && T=="/"){
                cout<<"error: division by zero"<<endl;
                return 0;
            }
            //to perform required operation and pushing the result into the stack,here we have
            //to use to_string() function to convert the float value to string before pushing.
            if(T=="+")
                st.push(to_string(val2 + val1));
            else if(T=="-")
                st.push(to_string(val2 - val1));
            else if(T=="*")
                st.push(to_string(val2 * val1));
            else if(T=="/")
                st.push(to_string(val2/val1));
        } 
        //if T is any operand then we just need to push it into the stack
        else{
            st.push(T);
        }
    } 
    
    //to print the result which will be the only one element in the stack
    cout<<"result = "<<stof(st.top());
    
    return 0; 
} 

Sample Input and output of above code:

Please enter an expression in post-fix notation:

Input:9.5 8 3.0 2 * 6 - / +

Output:error: division by zero

Please enter an expression in post-fix notation:

Input:2.0 3.3 +

Output: 5.3

Please enter an expression in post-fix notation:

Input : 3 4 * -2.5 /

Output: -4.8

Code Explainations:

Here we are evaluating of postfix expression by using stack.

The algorithm for evaluation of postfix expressions will be:


Step 1) Create a stack of string to store operands (or values).
Step 2) We need to scan the given expression and will do following for every scanned element.
a) If the element is a float number,we have to push it into the stack
b) If the element is any operator(+,-,*,/ etc), we need to pop two operands from stack. Then we have to evaluate the expression as <second operand >operator< first operand >and again need to push the result back to the stack

c) while evaluating expression we need to check for zero division error as well as like if first operand is 0.0 and the operator is division that is '/'
Step 3) When the expression is ended, the number at the top of the stack will be our required answer.

Note: While implementing this code I have taken care of the point that the given input expression will have space seperation between operands and operator. Also I have implemented it in such a way that if there is any zero division error occurs that is whenever we try to divide a number by 0 then it will raise an error message and just return, as in case Input:9.5 8 3.0 2 * 6 - / +

If you are having doubts regarding the working of this codes or anything else which is not being understood then please feel free to ask me in comment section I will be more then happy to solve your doubts!!

further for better understanding of code I have provided the comments in the code itself and also i am providing the code screenshots for quick reference

Code Screenshots:


Related Solutions

There was a person who answered this before, please don't answer again. Your handwriting is illegable...
There was a person who answered this before, please don't answer again. Your handwriting is illegable and the topic is jobs in American, not India. To the next person answering this, please don't look up the answer on Chegg and give me the same answer the previous poster gave. THIS IS AN ESSAY QUESTION SO PLEASE ANSWER THOROUGHLY AND DESCRIBE WHY: From The Economic Way of Thinking Name three areas where US governments should concentrate as far as providing jobs.
I submitted this before, but the question wasn't fully answered/correct. Can you please try again? Matheson...
I submitted this before, but the question wasn't fully answered/correct. Can you please try again? Matheson Electronics has just developed a new electronic device that it believes will have broad market appeal. The company has performed marketing and cost studies that revealed the following information: a. New equipment would have to be acquired to produce the device. The equipment would cost $120,000 and have a six-year useful life. After six years, it would have a salvage value of about $18,000....
THIS QUESTION WAS ANSWERED BEFORE BUT A-D. PLEASE ANSWER SECTION E. There is no mass transit...
THIS QUESTION WAS ANSWERED BEFORE BUT A-D. PLEASE ANSWER SECTION E. There is no mass transit in Cedar Grove, so Letecia’s goats are fascinated with buses and trains now that they live in SoCal. In fact, they spend anywhere between 30 and 150 minutes each day on some form of mass transit or other, and no length of time is any more likely than any other. a. Draw a graph of the distribution of the amount of time that any...
***PLEASE ANSWER QUESTION AGAIN (SOMEONE ELSE)- FIRST ONE WAS ANSWERED INCORRECTLY The cash records of Jasmin...
***PLEASE ANSWER QUESTION AGAIN (SOMEONE ELSE)- FIRST ONE WAS ANSWERED INCORRECTLY The cash records of Jasmin Company show the following four situations: 1) The June 30 bank reconciliation indicated that deposits in transit total $2,110. During July the general ledger account Cash shows deposits of $23,620, but the bank statement indicates that only $23,400 in deposits were received during the month. 2) The June 30 bank reconciliation also reported outstanding checks of $1,250. During the month of July, Jasmin Company...
I posted this question before and the person who answered it answered wrong.........please have someone else...
I posted this question before and the person who answered it answered wrong.........please have someone else try again The following information applies to the questions displayed below.] O’Brien Company manufactures and sells one product. The following information pertains to each of the company’s first three years of operations: Variable costs per unit: Manufacturing: Direct materials $28 Direct labor $15 Variable manufacturing overhead $5 Variable selling and administrative $3 Fixed costs per year: Fixed manufacturing overhead $580,000 Fixed selling and administrative...
Please answer with a new answer not one that has already been answered on here before....
Please answer with a new answer not one that has already been answered on here before. Many supervisors are not well-trained on the difficult task of terminating an employee and instead resort to other methods of forcing someone out of the organization. Methods include giving the employee unpleasant work tasks, reducing their hours, or modifying their jobs in some negative way. What are the ethical issues raised by this strategy and what are the risks to the organization?
BEFORE YOU ANSWER THIS QUESTION, PLEASE READ: I HAVE ALREADY POSTED THIS QUESTION MULTIPLE TIMES, AND...
BEFORE YOU ANSWER THIS QUESTION, PLEASE READ: I HAVE ALREADY POSTED THIS QUESTION MULTIPLE TIMES, AND I NEED HELP WITH THE JOURNAL ENTRIES. PLEASE INCLUDE THEM IN THE ANSWER. THANK YOU Overhead Variances, Four-Variance Analysis, Journal Entries Laughlin, Inc., uses a standard costing system. The predetermined overhead rates are calculated using practical capacity. Practical capacity for a year is defined as 1,000,000 units requiring 200,000 standard direct labor hours. Budgeted overhead for the year is $750,000, of which $300,000 is...
PLEASE ANSWER THIS QUESTION WITH THESE VALUES NOT ONE YOU ANSWERED WITH DIFFERENT VALUES!!! THANKS A...
PLEASE ANSWER THIS QUESTION WITH THESE VALUES NOT ONE YOU ANSWERED WITH DIFFERENT VALUES!!! THANKS A radio broadcast antenna is 36.00 km from your house. Suppose an airplane is flying 2.200km above the line connecting the broadcast antenna and your radio, and that waves reflected from the airplane travel 85.00 wavelengths farther than waves that travel directly from the antenna to your house. Part A Do you observe constructive or destructive interference between the direct and reflected waves? (Hint: Does...
CPT CODES FORTHE FOLLOWING (PLEASE DO NOT ATTEMPT TO ANSWER IF YOU HAVE NOT ANSWERED AT...
CPT CODES FORTHE FOLLOWING (PLEASE DO NOT ATTEMPT TO ANSWER IF YOU HAVE NOT ANSWERED AT LEAST (1000) QUESTIONS I WILL GIVE A THUMBS DOWN THANK YOU!! Bilateral ureteroneocystostomy Removal of complete cerebrospinal fluid shunt system, with replacement due to congenital hydrocephalus Open transluminal balloon angioplasty of both the left and right iliac artery Laparoscopic cholecystectomy with exploration of common duct Repair of nontunneled centrally inserted central VAD (without a port or pump) Excision of tonsil tags Diagnostic knee arthroscopy...
In java please Question: You are given a string s. Your task is to count the...
In java please Question: You are given a string s. Your task is to count the number of ways of splitting s into three non-empty parts a, b and c (s = a + b + c) in such a way that a + b, b + c and c + a are all different strings. For s = "xzxzx", the output should be countWaysToSplit(s) = 5. Consider all the ways to split s into three non-empty parts:
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT