I am trying to solve this code challenge:
Write a LMC program that calculates the sum of numbers provided by the user. Display the summation as output before halting the program. If the user has provided less than or equal to ten input values, then only sum even numbers. Odd numbers are ignored. If the user has provided more than ten values, then only sum any odd numbers subsequent to the tenth input. The existing summation of even numbers shall remain. If the user enters zero, at any point, then the summation is displayed.
For example:
Input values: 3, 3, 4, 0
Result:4Input values: 2, 3, 7, 0
Result: 2Input values: 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 0
Result: 43
My code
This is the code I ended up with:
start
INP
STA input
BRZ halt
LDA inputCounter
SUB ten
BRP afterTen
// Input <= 10
LDA input
STA isEven
SUB one
BRP oddNumber
LDA isEven
ADD one
STA isEven
SUB two
BRZ evenNumber
oddNumber LDA inputCounter
ADD one
STA inputCounter
BRA start
evenNumber LDA input
ADD evenSum
STA evenSum
LDA inputCounter
ADD one
STA inputCounter
BRA start
// Input > 10
afterTen LDA input
STA isEven
SUB one
BRP evenAfterTen
LDA isEven
ADD one
STA isEven
SUB two
BRZ oddAfterTen
evenAfterTen LDA inputCounter
ADD one
STA inputCounter
BRA start
oddAfterTen LDA input
ADD oddSum
STA oddSum
LDA inputCounter
ADD one
STA inputCounter
BRA start
// Display sum
halt LDA evenSum
ADD oddSum
OUT
HLT
// Variables
evenSum DAT 0
oddSum DAT 0
inputCounter DAT 0
isEven DAT 0
input DAT 0
// Constants
one DAT 1
two DAT 2
ten DAT 10
Problem
When running the above for the first example input, I already get the wrong output (0 instead of the expected 4):
Analysis
When I step through the code, I see that after having read the first input it gets into the correct section (Input <= 10), and correctly identifies the first number as odd. The input counter is correctly incremented, and the next input is taken.
So it continues for the other inputs, and once 0 is input, it correctly jumps to the last section to output the result.
But for the input 4 it also jumps to the oddNumber
section, and doesn't execute the code that subtracts 2 from it. By consequence the necessary addition to evenSum
is not performed either. Why is the BRP
instruction not branching?
Where is my mistake?