基于分支循环的LMC程序开发求助:内存地址91-95存1-5
Solution for LMC Loop-Based Memory Storage
Got it, let's tackle this LMC program requirement. The goal is to store values 1 to 5 into memory addresses 91 to 95 using loops (no hardcoded individual stores)—here's a clean, working approach tailored for the LMC simulator you're using:
Core Approach
We'll use three key variables to drive the loop:
- A counter to track how many values we've left to store (starts at 5)
- A current value that we increment each iteration (starts at 1)
- A target address that we increment each iteration (starts at 91)
The loop will repeat until the counter hits 0, performing these steps each time:
- Store the current value at the target address
- Increment the current value by 1
- Increment the target address by 1
- Decrement the counter by 1
- Check if we need to loop again
Full LMC Code
LDA COUNT ; Load loop counter into accumulator BRZ END ; Exit immediately if counter is 0 (safety check) LOOP LDA VALUE ; Load the value we need to store STA ADDR ; Store it at the current target address ; Increment the value for next iteration LDA VALUE ADD ONE STA VALUE ; Increment the target address for next iteration LDA ADDR ADD ONE STA ADDR ; Decrement the loop counter LDA COUNT SUB ONE STA COUNT BRZ END ; If counter is now 0, exit the loop BRA LOOP ; Otherwise, jump back to start of loop END HLT ; Halt the program ; Data section - initialize our variables COUNT DATA 5 ; Number of values to store (1-5) VALUE DATA 1 ; Starting value to store ADDR DATA 91 ; Starting memory address to write to ONE DATA 1 ; Constant for increment operations
How It Works (Line-by-Line)
- Data Section: We define our starting values here.
COUNTtells the loop how many times to run,VALUEis the first number we store,ADDRis the first memory location we write to, andONEis a reusable constant for increments. - Initial Check: The first
LDA COUNTandBRZ ENDis a safety measure—if someone accidentally setsCOUNTto 0, the program exits immediately instead of looping infinitely. - Loop Body:
LDA VALUE+STA ADDR: Writes the current number to the target memory address.- The next four lines increment our value by 1 and save it back.
- The following four lines increment our target address by 1 and save it back.
- Finally, we decrement the counter. If it hits 0, we jump to
ENDto halt; otherwise, we jump back toLOOPto repeat.
Testing in the Simulator
After running the program, check memory addresses 91 through 95—you should see:
- Address 91: 1
- Address 92: 2
- Address 93: 3
- Address 94: 4
- Address 95: 5
This avoids hardcoding individual STA 91, STA 92, etc., and uses a finite loop exactly as required.
内容的提问来源于stack exchange,提问作者Sam Hockham
相关产品推荐
相关产品推荐

