(For levels 3 and 4, your task is to write programs in the Alphatron machine language. Your submissions will be two .alp programs, called loop.alp and prime.alp. Your files should NOT contain the word RUN, or any inputs!!!)
Write the Alphatron program loop.alp, a program which reads in two numbers X and Y. The program needs to loop X times, printing Y each time.
I.e. if the input is
4
3
then the output is
3
3
3
3
Assistant
To solve this problem, we need to create an Alphatron machine program loop.alp that reads two numbers, X and Y, and then prints Y exactly X times.
The Alphatron machine has the following available operations and syntax:
Registers: A, B, C
Operations:
GET A – Read an input number into register A.
PUT A – Output the value from register A.
LOAD A N – Load the constant number N into register A.
ADD A B – Add the value in register B to register A (A = A + B).
SUBTRACT A B – Subtract the value in register B from register A (A = A - B).
GOTO N – Unconditionally jump to label N.
IFZERO A N – If the value in register A is zero, jump to label N.
Labels are defined with N1:, N2:, etc.
Here is the step-by-step plan:
Read X and Y: Use GET instructions to read X into register A and Y into register B.
Initialize Counter: Load 1 into register C to use for decrementing.
Loop Structure:
Check if A is zero: If A is zero (IFZERO A N2), we have completed the loop and can end the program.
Output Y: Use PUT B to output Y.
Decrement A: Subtract 1 from A (SUBTRACT A C) to reduce the loop counter.
Repeat: Use GOTO N1 to loop back to the start of the loop.
End the Program: Label N2 marks the end of the loop.
Here is the complete loop.alp program:
GET A
GET B
LOAD C 1
N1:
IFZERO A N2
PUT B
SUBTRACT A C
GOTO N1
N2:
This program works as follows:
It reads X and Y into registers A and B respectively.
It initializes a decrement value C as 1.
It enters a loop (N1):
If A is zero, it jumps to N2, ending the loop.
It outputs the value in B.
It decrements A by 1.
It loops back to N1.
When the loop ends (N2), the program terminates.
Note: Ensure that your loop.alp file contains precisely the code above and does not include any extra inputs or the word RUN.