Hi, I need help with computation using a stack homework. It was a C++ programmin
ID: 3700864 • Letter: H
Question
Hi, I need help with computation using a stack homework. It was a C++ programming homework question will be posted below. Please use CLASS to do this program and what I need was a program which can calculate entered the number in infix format using a set of + - * / Thank you for your help... Also, include the output.....
--------------------- Question -----------------
Homework #5A-Computation Using a Stack Write a program which will take a calculation, entered in infix format. using a set of numbers and the operands +, -, ,/and will determine the result. Use the algorithm demonstrated in class to implement the solution, but do it using a singly linked list to emulate two stack ADT's. Extra credit will be given if you can support parentheses. Do not use the STL library for the stacks, but build your own ADTs.Explanation / Answer
Answer :
C++ Code:
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <stack>
#include <string.h>
using namespace std;
bool operator_check(char ch)
{
if (ch=='+' || ch=='-' || ch=='*' || ch=='/')
return true;
else
return false;
}
int evaluate_exp(int op1, int op2, char op)
{
int ans;
switch(op){
case '+':
ans = op2 + op1;
break;
case '-':
ans = op2 - op1;
break;
case '*':
ans = op2 * op1;
break;
case '/':
ans = op2 / op1;
break;
}
return ans;
}
int main()
{
int out;
char exp[1000], buffer[15];
int i,op1, op2, len, j, x;
stack<int> s;
cout<<"enter an expression"<<endl;
gets(exp);
len = strlen(exp);
j = 0;
for(i=0; i<len;i++){
if(exp[i]>='0' && exp[i]<='9'){
buffer[j++] = exp[i];
}
else if(exp[i]==' '){
if(j>0){
buffer[j] = '';
x = atoi(buffer);
s.push(x);
j = 0;
}
}
else if(operator_check(exp[i])){
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(evaluate_exp(op1, op2, exp[i]));
}
}
out=s.top();
cout<<"answer is "<<out;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.