id: 8
title: Compare and Branch
subtitle: Letting the program decide
description: Learn CMP and conditional branch instructions

tutorial:
  - title: Up to now...
    text: >
      Programs ran top to bottom in order. With **branching**, the program can
      finally make decisions!
  - title: CMP — compare
    text: >
      `CMP` compares two values and remembers the result (the values themselves
      are unchanged):
    code: |
      CMP R0, #10    ; compare R0 with 10
  - title: Conditional branches
    text: >
      After comparing, use **B** (Branch) to jump:
    code: |
      BEQ label  ; jump if Equal
      BNE label  ; jump if Not Equal
      BGT label  ; jump if Greater Than
      BLT label  ; jump if Less Than
      B   label  ; unconditional jump
  - title: Labels
    text: >
      A **label** is a marker in your code that branches jump to. Add a colon after the name:
    code: |
      CMP R0, #10
      BGT big
      MOV R1, #0     ; R0 <= 10
      B done         ; skip the next part
      big:
      MOV R1, #1     ; R0 > 10
      done:
      XHLT

goal: R0=**15**. If R0 > 10 then R1 = **1**; otherwise R1 = **0**

initialState:
  registers:
    R0: 15

testCases:
  - init:
      registers:
        R0: 15
    expected:
      registers:
        R1: 1
  - init:
      registers:
        R0: 5
    expected:
      registers:
        R1: 0
  - init:
      registers:
        R0: 10
    expected:
      registers:
        R1: 0

hints:
  - "Default R1 to 0, then compare R0 with 10"
  - "If R0 > 10, jump to a label that sets R1 to 1"
  - "Answer: MOV R1, #0 / CMP R0, #10 / BLE done / MOV R1, #1 / done: XHLT"

starThresholds: [5, 7, 9]

starterCode: |
  ; If R0 > 10 then R1 = 1
  ; Otherwise R1 = 0


  XHLT

showMemory: false
