Exercise 1: Identifying What Actually Ends the 6502 Loop — Possible Solution ==================================================================== TRACING X THROUGH THE FIVE ITERATIONS ------------------------------ Iteration 1: X starts at 0. ARRAY[0] is added. INX makes X = 1. CPX #5 compares 1 to 5 -> not equal. BNE branches back. Iteration 2: X = 1. ARRAY[1] added. INX makes X = 2. CPX -> not equal. BNE branches back. Iteration 3: X = 2. ARRAY[2] added. INX makes X = 3. CPX -> not equal. BNE branches back. Iteration 4: X = 3. ARRAY[3] added. INX makes X = 4. CPX -> not equal. BNE branches back. Iteration 5: X = 4. ARRAY[4] added (the last real array element). INX makes X = 5. CPX #5 now compares 5 to 5 -> EQUAL. THE INSTRUCTION THAT ACTUALLY ENDS THE LOOP ------------------------------ BNE is the instruction that actually ends the loop. CPX #5 only sets the processor's flags based on comparing X to 5 — per this chapter's own explanation, CPX sets the same flags cpu8bit1-3 already covered, in particular the Zero flag, which becomes SET specifically when the two compared values are equal. CPX itself never branches anywhere; it only prepares the flags for whatever branch instruction comes next. BNE is a conditional branch that checks whether the Zero flag is CLEAR ("not equal"). Once CPX sets Z on the fifth pass (because X now equals 5), BNE's own condition — Z clear — is no longer satisfied, so BNE does NOT branch back to LOOP this time, and execution falls through to DONE instead. WHAT CONDITION IT'S CHECKING ------------------------------ BNE checks whether the Zero flag is clear, meaning "the last comparison found the two values were NOT equal." The loop keeps running for as long as that condition holds (X hasn't reached 5 yet) and stops the very first time it fails (X has reached exactly 5). WHY THIS WORKS AS AN ANSWER ------------------------------ It traces X's value through every iteration precisely, correctly distinguishes CPX's role (setting flags only, never branching) from BNE's role (the actual branch decision), and states exactly which flag and which condition BNE is checking rather than vaguely saying "it checks if the loop is done."