Hack Assembly Language - Calculating R0 + ... +R1..

  • Get the value at R0
  • Get the value at R1
  • Find the sum of R0 + (R0 + 1) + (R0 + 2) + ... (R1)

So here is the code I have:
// *        Find sum of R0 + .. + R1                    *
// *        For example: R0 = 10                        *
// *                     R1 = 12                        *
// *        10 + 11 + 12 = 33                           *
// *        Assume R1 is always greater than R0         *
// *        Store it in R2                              *
 
 
// Find how many times we need to iterate
@R1                        // Higher value
D = M                      // Store it in Register D
@R0                        // Lower value
A = M                      // Store it in Register A
D = D - A                  // Find the difference
 
// And store it in M[counter]
@counter                // In our example 12 - 10 = 2
M = D                   // M[counter] = 2
 
// Store the lower value we have at M[sum]
@R0
D = M
@sum
M = D
 
(LOOP)
@counter
D = M             // Load M[counter] to Register D
 
// If D == 0, i.e. if counter == 0
// we do not need to do any calculations, 
// jump to (STORE)
@STORE
D;JEQ            
 
// If D != 0, ie if counter != 0
// we have some arithmetic to do..
@R0
D = D + M        // D = D + R0
                 // For example: 
                 // Iteration 1: D = 2 + 10 ==> D = 12
                 // Iteration 2: D = 1 + 10 ==> D = 11
 
 
// Add the value we have in Register D to the value we have in M[sum]
@sum                
A = M            // M[sum] = M[sum] + D
D = D + A        // Iteration 1: M[sum] = 10 + 12 ==> M[sum] = 22 
@sum             // Iteration 2: M[sum] = 22 + 11 ==> M[sum] = 33
M = D            
 
// Decrement M[counter]
@counter            
M = M - 1        // Iteration 1: M[counter] = 1
                 // Iteration 2: M[counter] = 0
 
// Jump to (LOOP)
@LOOP
0;JMP
 
(STORE)
@sum
D = M
@R2
M = D
 
// Clean up sum..
@sum
M = 0
 
(END)
@END
0;JMP

And let 's see it in action, we know that 1 + 2 + 3 + ... + 100 = 5050.
Here is the code above in action: