Assembly Language Fundamentals

Beginner
Version:
1.1

Conditional Jumps and Loops

Introduction

You’ve already seen how to jump using JP and JR. Those jumps were unconditional, they always happened.

But what if you only want to jump sometimes? For example:

That’s where conditional jumps come in

What Is a Conditional Jump?

A conditional jump works like an if statement. It tells the program:

“Only jump if a certain condition is true.”

In BASIC, this looks like:

10 IF X = Y THEN GOTO 500

In Z80 assembly, you don’t use IF, you use jump instructions that check flags in the CPU

The Flag Register (F) and the Zero Flag (Z)

The F register is 8 bits, each representing information about the last instruction’s result:

The Z80 processor sets a series of flags in the F register after most instructions. These flags record information about the result of the operation and are often used for decision-making (for example, in conditional jumps).

Here’s what each flag means:

For now, we focus on Z (Zero)

How the Z Flag Works

Every time you perform an operation, the Z flag updates automatically:

The DEC Instruction

DEC means decrease by 1.

Example:

DEC A

Subtracts 1 from the value in A.

You can use DEC with registers A, B, C, D, E, H, L.

Don’t confuse:

C the register vs. C the flag — they are completely different

JR NZ, label — Conditional Looping

The key instruction here:

JR NZ, loop

Which means:

Plain English:

“Jump back to loop if the last result was not zero.”

This is the foundation of loops that stop when a counter hits zero

Example Program: Print 'A' Ten Times

       ORG 256

       LD C, 10        ; Counter
       LD A, 'A'       ; ASCII for letter A

loop:
       RST 8
       DEFB 158
       DEC C
       JR NZ, loop     ; If C ≠ 0, keep looping
       RET

What Happens Here

Why Use C Instead of A?

You could loop by decrementing A, but using C is a good habit:

Exercises

Write a program that:

  1. Loads A with ASCII Z (90)
  2. Prints it
  3. Decreases A
  4. Loops until it reaches A (65)

Use DEC A and JR NZ,label

Summary

Previous Module
Next Module