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

Assume that a machine has a single register and six instructions as follows: LD

ID: 3716571 • Letter: A

Question

Assume that a machine has a single register and six instructions as follows:

LD       A                      Places the operand A into the register

ST        A                      Places the contents of the register into the variable A

AD       A                      Adds the contents of the variable A to the register

SB        A                      Subtracts the contents of the variable A from the register

ML       A                      Multiplies the contents of the register by the variable A

DV       A                      Divides the contents of the register by the variable A

Write a program in C++ that accepts a postfix expression containing single letter operands and the operators +, -, *, / and prints a sequence of instructions to evaluate the expression and leave the result in the register. Use variables of the form TEMPn as temporary variables. For example, using the postfix expression ABC+DE-/ should print the following:

LD       B

ML       C

ST        TEMP1

LD       A

AD       TEMP1

ST        TEMP2

LD       D

SB        E

ST        TEMP3

LD       TEMP2

DV       TEMP3

ST        TEMP4

Explanation / Answer

import java.io.*;
class Stack
{
private int[] a;
private int top,m;
public Stack(int max)
{
m=max;
a=new int[m];
top=-1;
}
public void push(int key)
{
a[++top]=key;
}
public int pop()
{
return(a[top--]);
}
}
class Evaluation{
public int calculate(String s)
{
int n,r=0;
n=s.length();
Stack a=new Stack(n);
for(int i=0;i<n;i++)
{
char ch=s.charAt(i);
if(ch>='0'&&ch<='9')
a.push((int)(ch-'0'));
else
{
int x=a.pop();
int y=a.pop();
switch(ch)
{
case '+':r=x+y;
break;
case '-':r=y-x;
break;
case '*':r=x*y;
break;
case '/':r=y/x;
break;
default:r=0;
}
a.push(r);
}
}
r=a.pop();
return(r);
}
}
class PostfixEvaluation
{
public static void main(String[] args)throws IOException
{
String input;
while(true)
{
System.out.println("Enter the postfix expresion");
input=getString();
if(input.equals(""))
break;
Evaluation e=new Evaluation();
System.out.println("Result:- "+e.calculate(input));
}
}
public static String getString()throws IOException
{
DataInputStream inp=new DataInputStream(System.in);
String s=inp.readLine();
return s;
}
}

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