Search code examples
microprocessors8085

Assembly level programming to find the factorial


MVI B 07h
LXI H 0007h
LXI D 0007h
DCR B
LOOP1: DCR B
MOV C B
INR B
LOOP: DAD D
DCR C
JNZ LOOP
MOV E L
MOV D H
DCR B
JNZ LOOP1
HLT

I couldn't find out the problem in my code. Can you please help me out? It's giving me partially wrong answer. The two LSB bits are correct but not the MSBs.


Solution

  • I'm not sure why you're doing the extra decrement (followed by the increment) at the LOOP1 label to the B register but when B is one it causes C to become 0, which then wraps around to FFh and performs the multiply loop another 255 times.

    Instead why don't you take out the DCR B / INR B and before the multiply loop just set the H register to 0. The full program would look like this:

    MVI B, 07h
    LXI H, 0007h
    LXI D, 0007h
    DCR B
    
    LOOP1:
        MOV C, B
        LXI H, 0
    
        LOOP:
            DAD D
            DCR C
            JNZ LOOP
    
        MOV E, L
        MOV D, H
        DCR B
        JNZ LOOP1
    
    HLT