Skip to main content
Be Bitwise

Counting Loop

Use a loop to count from 0 to 5. Demonstrates jumps, comparison, and incrementing.

Loops in machine code are built from the same compare-and-jump pattern as conditionals, but the jump target points backwards to an earlier instruction. The CPU has no concept of a 'loop' — it just follows the program counter. When a JNZ instruction sends PC back to an earlier address, the effect is repetition. Every for-loop and while-loop compiles down to this pattern.

Simulator

Loading simulator...

Walkthrough Guide

  1. 1

    Initialise the counter and target

    Do this: Step through both MOV instructions

    Watch for: R0 = 0 (counter), R1 = 5 (target)

    R0 will count up from 0. R1 holds the target value we are counting towards. These are just registers holding numbers — the CPU does not know one is a 'counter'.

  2. 2

    First loop iteration

    Do this: Step through ADD, CMP, and JNZ

    Watch for: R0 increments to 1, CMP sets no zero flag (1 != 5), JNZ jumps back to the loop label

    ADD R0, #1 increments the counter. CMP compares it to the target — since 1 != 5, the zero flag stays clear. JNZ (jump if NOT zero) sees the flag is clear and jumps back to the loop label.

  3. 3

    Watch subsequent iterations

    Do this: Continue stepping or use Run to watch the loop repeat

    Watch for: R0 increments through 2, 3, 4, 5. Each time JNZ jumps back until R0 reaches 5

    Each iteration follows the same pattern: increment, compare, jump back. The CPU has no loop counter built in — it is just re-executing the same instructions because PC keeps getting reset to the loop address.

  4. 4

    Loop exit

    Do this: Step through the final CMP and JNZ when R0 = 5

    Watch for: CMP sets the zero flag (5 == 5), JNZ does NOT jump, execution falls through to HALT

    When R0 finally equals R1, CMP sets the zero flag. JNZ checks the flag and this time does not jump — PC simply advances to HALT. The loop ends because the jump condition was no longer met.

Objectives

  • •Watch R0 increment from 0 to 5
  • •See the PC jump back to the loop label each iteration
  • •Notice the zero flag gets set only when R0 equals R1
  • •Count how many cycles it takes to complete

Hints

  • The JNZ instruction jumps when the zero flag is NOT set