Skip to content
BetterDL

Program loop

Also called: loop, loops, counting loop

A section of a program that repeats, built from a backward jump, with a conditional branch that exits when a count or test is met.

A CPU has no built-in loop statement. A loop is built from jumps:

A typical Tiny8 counting loop keeps a counter in memory. Each pass loads it, subtracts 1 (or some step), and stores it back. The SUB sets Z, so JZ can leave the loop when the counter reaches 0. Otherwise a JMP goes back to the top.

When counting instructions or cycles in a loop, be careful with the last pass. It usually leaves through the JZ, so it skips the JMP. A loop that runs n times often executes the JMP only n − 1 times.

A bug to watch for: if the counter never hits exactly 0 (say you subtract 2 from an odd number), Z never becomes 1 and the loop wraps around 256 and keeps going.

Worked example

Example

Counting down by 2

Tiny8 memory: 0: LOAD E (1E), 1: SUB F (4F), 2: STORE E (2E), 3: JZ 5 (65), 4: JMP 0 (50), 5: HALT (00). M[E] = 4, M[F] = 2.

  1. 1.

    Pass 1: LOAD E, SUB F, STORE E leave M[E] = 2 and Z = 0. JZ isn't taken; JMP 0 goes back.

  2. 2.

    Pass 2: M[E] = 0 and Z = 1. JZ 5 is taken, so the JMP is skipped.

  3. 3.

    HALT at address 5.

  4. 4.

    Instructions executed: 5 + 4 + 1 = 10. Cycles: (6 + 6 + 6 + 5 + 5) + (6 + 6 + 6 + 5) + 5 = 28 + 23 + 5 = 56.

Common mistakes

  • Counting the JMP on every pass. The last pass leaves through the JZ.

  • Counting listing lines instead of executed instructions when finding cycles or CPI.

  • Writing a loop whose counter skips over 0, so it never exits.

Practice Program loop

Interactive questions with instant feedback and a worked solution for every wrong answer.

Basic CPU / Computer Architecture lesson full course

Learn it step by step

Program loop is taught in Basic CPU / Computer Architecture.