CSC213 · 2079 · 5 marks
Write the program for the following statement using three, single, zero address instructions. X = (A*B+C-D) / (E+F*G)
Write the program for the following statement using three, single, zero address instructions. $X = (AB+C-D) / (E+FG)$ [5]
Given
Given data:
- Expression: $X = (AB + C - D) / (E + FG)$
- Required representations: three-address, one-address (single), zero-address instructions.
No numeric values are involved; this is a symbolic instruction-set problem.
Solution
1. Three-Address Instructions
Format: OP DEST, SRC1, SRC2
MUL R1, A, B ; R1 = A * B
ADD R1, R1, C ; R1 = A*B + C
SUB R1, R1, D ; R1 = A*B + C - D
MUL R2, F, G ; R2 = F * G
ADD R2, E, R2 ; R2 = E + F*G
DIV X, R1, R2 ; X = (A*B + C - D) / (E + F*G)
Total: 6 instructions
2. One (Single) Address Instructions
Format uses the Accumulator (AC): OP M means $AC = AC ; \text{OP} ; M[M]$
LOAD F ; AC = F
MUL G ; AC = F*G
ADD E ; AC = E + F*G
STORE T ; T = E + F*G
LOAD A ; AC = A
MUL B ; AC = A*B
ADD C ; AC = A*B + C
SUB D ; AC = A*B + C - D
DIV T ; AC = (A*B + C - D) / (E + F*G)
STORE X ; X = result
Total: 10 instructions
Note: The denominator is computed first so that only one temporary (T) is needed and the numerator can remain in the accumulator for the final DIV. An alternative 12-instruction version computes both sub-expressions, stores both, then reloads, which works but uses two extra instructions. The 10-instruction form is the standard optimal solution.
3. Zero-Address Instructions (Stack-Based)
Operands are implicit on the stack. Uses PUSH / POP for memory access and arithmetic on top two elements.
Postfix (reverse Polish) of the expression: $$A,B,,C,+,D,-,E,F,G,,+,/$$
PUSH A ; A
PUSH B ; A, B
MUL ; A*B
PUSH C ; A*B, C
ADD ; A*B+C
PUSH D ; A*B+C, D
SUB ; A*B+C-D
PUSH E ; A*B+C-D, E
PUSH F ; A*B+C-D, E, F
PUSH G ; A*B+C-D, E, F, G
MUL ; A*B+C-D, E, F*G
ADD ; A*B+C-D, E+F*G
DIV ; (A*B+C-D)/(E+F*G)
POP X ; X = result
Total: 14 instructions
Summary Table
| Instruction Type | No. of Instructions |
|---|---|
| Three Address | 6 |
| One Address | 10 |
| Zero Address | 14 |
Key Observation: As the number of addresses per instruction decreases, the number of instructions needed increases.
For the one-address form the optimal solution needs 10 instructions; a version that stores and reloads both operands needs 12. Both are logically correct, and 10 is the minimal standard form.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.