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

I need a code in C++ for this please help. Evaluate the following post x express

ID: 3884938 • Letter: I

Question

I need a code in C++ for this please help.

Evaluate the following post x expressions by using the algorithm given in this chapter. Show the status of the stack after each step of the algorithm. Assume the following values for the identi ers: a = 7, b = 3, c = 12, d = –5, e = 1.

a. a b c + –

b. a b c – d * +

c. a b +c – d e * +   

The pseudocode algorithm is then for (each character ch in the string) if (ch is an operand) Push the value of the operand ch onto the stack else // ch is an operator named op Evaluate and push the result oper Pop the stack and2 = top of stack and! = top of stack oper Pop the stack result = operand1 op operand2 Push result onto the stack

Explanation / Answer

postfix.cpp

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <stack>
#include <string.h>

using namespace std;

//print the stack elements
void print(stack<int> &s)
{

if(s.empty())
{
cout << endl;
return;
}
int x= s.top();
s.pop();
print(s);
s.push(x);

cout << x << " ";
}

//check for operator character
bool isOperator(char ch)
{
if (ch=='+' || ch=='-' || ch=='*' || ch=='/')
return true;
else
return false;
}

//perform the arithmetic operations
int performOperation(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()
{
char exp[1000], buffer[15];
int i,op1, op2, len, j, x;
stack<int> s;
  
//get the postfix expression from user
printf("Enter a Postfix Expression: ( e.g. 23 34 * ) ");
gets(exp);
len = strlen(exp);
j = 0;

for(i=0; i<len;i++){


if((exp[i]>='0' && exp[i]<='9') || isOperator(exp[i])&& (exp[i+1]>='0' && exp[i+1]<='9')){
buffer[j++] = exp[i];
}
else if(exp[i]==' '){
if(j>0){
buffer[j] = '';
x = atoi(buffer); //if it is integer convert into integer and push in stack
s.push(x);

j = 0;
}
}

//if character is operator then perform operation
else if(isOperator(exp[i])){
cout<<" stack values: "<<endl;
print(s);
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();

s.push(performOperation(op1, op2, exp[i]));
}
}

printf(" Answer is %d ", s.top());

return 0;
}

output:   

Enter a Postfix Expression: ( e.g. 23 34 * )
7 3 + 12 - -5 1 * +

stack values:

7 3
stack values:

10 12
stack values:

-2 -5 1
stack values:

-2 -5

Answer is -7

Process returned 0 (0x0) execution time : 25.708 s
Press any key to continue.

//unable to upload image format output.. i have given in word format.. for any clarification please do comments..

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