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

Write a simple calculator program in C++ using a dynamic stack. The calculator s

ID: 3762126 • Letter: W

Question

Write a simple calculator program in C++ using a dynamic stack. The calculator should handle addition, subtraction, division, multiplication and parentheses expressions. The add() function pops the first two values off the stack, adds them together, and pushes the sum onto the stack. The sub() function pops the first two values off the stack, subtracts the second value from the first, and then pushes the difference onto the stack. The mult() pops the top two values off the stack, multiplies them, and pushes their product onto the stack. The div() pops the top two values off the stack, divides the second value by the first, and pushes the quotient onto the stack. Your program must use inheritance. Be sure to provide descriptive comments for every line of code.

To help guide your algorithm design, sample prefix notation input with answers are given below: * 8 ( + 7 12) => 8 * ( 7 + 12 ) = 152 ( + 7 ( * 8 12 ) ( * 2 (+ 9 4) 7 ) 3 ) => 7+8*12+2*(9+4)*7+3 = 148

Explanation / Answer

#include <iostream>
#include <string.h>
#include <stack>
#include <sstream>
#include <stdlib.h>
#include<vector>
using namespace std ;

//checking for operator
bool operation(char b)
{
if(b=='+' || b=='-' || b=='*' || b=='/'){
return true;
}
return false;
}

int evaluate ( const std::string& expression )
{

int l,r,ans;
std::stringstream postfix(expression);
std::vector<int> temp;
std::string s;
while ( postfix >> s )
{
if( operation(s[0]) )
{
//Popping out two elements
r = temp.back();
temp.pop_back();
l = temp.back();
temp.pop_back();
cout<<r<<" "<<l;
// Performing operation
switch( s[0])
{
case '+': ans = l + r ; break;
case '-': ans = l - r ; break;
case '*': ans = l * r ; break;
case '/': ans = l / r ; break;
}

temp.push_back( ans ); // storing answer
}
else
{
temp.push_back( std::stoi(s) );
}
}

return temp[0] ; //returning answer
}
int main()
{
//reading expressin from user
string res;
cout<<"Enter expression: ";
cin>>res;
  
cout<<"The result of the expression is:"<<evaluate(res);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote