Loops

loops

Pseudocode:

sum=0
for(int num=0; num<10; num=num+1) {
  sum=sum+num
}

Assembler:

// sum=0
@sum
M=0
// n=0
@num
M=0
(LOOP)
// D=n-10
@num
D=M
@10
D=D-A
// if D >= 0 then goto DONE
@DONE
D;JGE
// sum = sum + num
@num
D=M
@sum
M=D+M
// n=n+1
@num
M=M+1
@LOOP
1;JMP

If you follow the code in the CPU emulator, you will see than the sum variable is stored in RAM[16] and num is in RAM[17].

Last modified September 25, 2024: Examples translations of "if" and "for". (7e1cef9)