Assume a machine that has a single register and 6 instructions.
\(\begin{array}{ l l l }
\texttt{LD} & \texttt{A} & \textit{places the operand A into the register}\\
\texttt{ST} & \texttt{A} & \textit{places the contents of the register into the variable A}\\
\texttt{AD} & \texttt{A} & \textit{adds the contents of the variable A to the register}\\
\texttt{SB} & \texttt{A} & \textit{substracts the contents of the variable A from the register}\\
\texttt{ML} & \texttt{A} & \textit{multiplies the contents of the register by the variable} \\
\texttt{DV} & \texttt{A} & \textit{divides the contents of the register by the variable}\\
\end{array}\)
Write a program that accepts a postfix expression containing a single-letter operands and the operators +, -, *, and / and prints a sequence of instructions to evaluate the expression and leave the result in the register. Use variables of the form \texttt{TEMP}n as temporary variables. For example, using the postfix expression ABC*+DE-/ should print the following:
\(\begin{array}{ l l }
\texttt{LD} & \texttt{B} \\
\texttt{ML} & \texttt{C} \\
\texttt{ST} & \texttt{TEMP}1 \\
\texttt{LD} & \texttt{A} \\
\texttt{AD} & \texttt{TEMP}1 \\
\texttt{ST} & \texttt{TEMP}2 \\
\texttt{LD} & \texttt{D} \\
\texttt{SB} & \texttt{E} \\
\texttt{ST} & \texttt{TEMP}3 \\
\texttt{LD} & \texttt{TEMP}2 \\
\texttt{DV} & \texttt{TEMP}3 \\
\texttt{ST} & \texttt{TEMP}4 \\
\end{array}\)
Difficulty level

This exercise is mostly suitable for students
typedef char element[N];
typedef struct {
element data[N];
int top;
} stack;
int is_operand(char c)
{
return (c>='a' && c<='z' || c>='A' && c<='Z' );
}
int is_operator(char c)
{
return (c=='*' || c=='-' || c=='/' || c=='+');
}
char *op(char c)
{
if(c=='+') return "AD";
if(c=='-') return "SB";
if(c=='*') return "ML";
if(c=='/') return "DV";
}
char * append_char_to_string(char * s, char c)
{
size_t len = strlen(s);
char *str2 = (char *) malloc((unsigned)(len + 1 + 1)); /* one for extra char, one for trailing zero */
strcpy(str2, s);
str2[len] = c;
str2[len + 1] = '\0';
return str2;
}
void sequence(char *str)
{
int i,j;
element opnd2,opnd1;
stack s= CreateStack();
j=1;
for(i=0;str[i];i++)
{
if(is_operand(str[i]))
{
Push(&s,append_char_to_string("",str[i]));
}
else
{
if(is_operator(str[i]))
{
Top(s,&opnd2); Pop(&s);
Top(s,&opnd1); Pop(&s);
printf("LD\t%s\n",opnd1);
printf("%s\t%s\n",op(str[i]),opnd2);
printf("ST\tTEMP%d\n",j);
Push(&s,append_char_to_string("TEMP",j+'0'));
j++;
}
}
}
}
void display(stack s)
{
element e;
while(Top(s,&e))
{
printf("%s\n",e);
Pop(&s);
}
}
int main()
{
char str[N];
printf("Enter a postfix expression\n");
scanf("%s",str);
sequence(str);
getch();
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
