Multiplication in MARIE - MARIE-js/MARIE.js GitHub Wiki
The goal of this section is for you to write some code for multiplying two integers together, especially negative integers. This page explains how to multiply integers that are both non-negative.
Since we can only add and subtract in MARIE, there is no multiply command in MARIE. Instead we can use a combination of Add and Subt instructions to perform iterative addition and terminate the program once it computes the result.
Explanation
Iterative addition is the most simplest method for performing multiplication on integers. For example, the expression 3*4 can be expressed as 3 added to itself 4 times: i.e. 3+3+3+3. As multiplication is commutative (i.e. order of multiplying numbers does not matter), this is also the same as 4 is added to itself 3 times: 4+4+4.
Selection statements
There are no if or else statements in MARIE, as implementing them is a bit complicated and would require several instructions. Instead we use Skipcond. Skipcond (num) skips the next line if a certain condition is true (which is explained in the MARIE Instruction Set).
Writing the Code
So what we need for the expression X*Y are two variables, X and Y.
What we can do is to allow the user to input integers into the two variables like so:
INPUT
Store X
INPUT
Store Y
The idea is we are going to add X, Y Times.
For this code, we need to load the variable num into the accumulator, then adds X to it and stores it back into the variable num. Then it loads Y into the accumulator and subtracts 1 from it and stores it back into Y. Then it uses the Skipcond 400 statement to check if Y is equal to 0. If it is it will 'Jump' over the Jump loop command and loads the number and outputs the result before halting.
Now we are going to look at the main loop - this is because we need to check when Y is equal to 0. So the main loop will look something like:
loop, Load num
Add X
Store num
Load Y
Subt one
Store Y
Skipcond 400
Jump loop
Load num
Output
Halt
Now, we need to declare the variables. So:
X, DEC 0
Y, DEC 0
one, DEC 1
num, DEC 0
Full Code
/ Prompt user to type in integers
INPUT
Store X
INPUT
Store Y
/ Loop for performing iterative addition
loop, Load num
Add X
Store num
Load Y
Subt one
Store Y
Skipcond 400 / have we completed the multiplication?
Jump loop / no; repeat loop
/ yes, so exit the loop
/ Output result to user then halt program
Load num
Output
Halt
/ Declare labels here
X, DEC 0
Y, DEC 0
one, DEC 1
num, DEC 0