8086汇编语言中的嵌套循环

时间:2012-10-09 13:40:22

标签: loops assembly nested-loops x86-16 tasm

我对如何使用循环来获取此程序中的期望输出存在问题,

我想要做的是从用户那里输入任意数字,然后按降序对该数字进行排序,

我在这里尽力解释评论中代码的每一步。

这是我的代码,

STSEG SEGMENT
        DB 64 DUP(?)
STSEG ENDS

DTSEG SEGMENT
        SNAME    DB 24 DUP("$")


DTSEG ENDS

CDSEG SEGMENT
    MAIN PROC
    ASSUME CS:CDSEG, DS:DTSEG, SS:STSEG

    MOV AX,DTSEG
    MOV DS,AX
    MOV ES, AX     ;ES:DI


    MOV DX, OFFSET STRNG1
    MOV AH,09
    INT 21H

    XOR DX,DX


      MOV BYTE PTR SNAME, 40
      MOV DX, OFFSET SNAME  

      MOV AH, 0AH
      INT 21H


      PUSH DX ;Hold the input number in a stack until we clear the screen and set the cursor
      ; The clear screen and cursor position code is here which i didn't really mention.

      ;What we need to do now is to compare first number to each other number and store the greatest


 of two on first position.


      MOV BX,DX ;Copy un-sorted number to BX, 

      MOV AX,BX[1] ;the length of the number which is stored on the first position of the string
      XOR AH,AH      ;Empty AH
      MOV CL,AL  ;MOVE AL into CL for looping 6 times
      SUB CL,1

      MOV SI,02H ;the number is stored in string array from the 2nd position


;Suppose the input number is the following,
      ;[6][3][9][1][8][2][6]

      ;this is how it should work,


      ; Loop 6 times , CX = 6
      [7][6][3][9][1][8][2][6] ; 7 is length of the number which is already copied in CX above.
      ; but we need 6 iterations this is why we subtract 1 from CL above.

      ; 6 > 3 ? 
      ; Yes, then BX[SI] = 6 and BX[SI+1] = 3
      ; 6 > 9 ?
      ; NO, then BX[SI] = 9  and BX[SI+2] = 6
      ; 9 > 1   
      ; Yes, then BX[SI] = 9 and BX[SI+3] = 1
      ; 9 > 8
      ; Yes, then BX[SI] = 9 and BX[SI+4] = 8 
      ; 9 > 2
      ; Yes, then BX[SI] = 9 and BX[SI+5] = 2 
      ; 9 > 6
      ; Yes, then BX[SI] = 9 and BX[SI+6] = 6

; After first iteration the incomplete sorted number is,
;[9][3][6][1][8][2][6]

  ;Similarly here i need to loop 5 times now by comparing the 2nd number which is a 3 with all ;the number after it and then loop 4 times then 3 times then two times and then 1 time.


     L1: 
        ;Loop 1 must iterate 6 time for the supposed input number, 
;but i couldn't be able to write the proper code as i always get out of registers. kindly help me out   

        L2:


        LOOP L2


     Loop L1

请帮助我完成我已经停留的嵌套循环。

1 个答案:

答案 0 :(得分:2)

循环使用(e)cx。

所以你必须保留外部循环的cx,例如:推送cx(在L2之前)并在循环L2之后弹出:

    mov  cx,5
L1:
    push cx
    mov  cx,6
L2:
    . . . do stuff inner
    loop L2
    pop cx
    . . . do stuff outer 
    loop L1

或者记住,循环大致等于dec cx jnz,例如。

    mov dx,5
L1:
    mov  cx,6
L2:
    ... do stuf inner
    loop L2
    .. do stuff outer
    dec dx
    jnz L1

可能出现一个错误意图并且意味着作为读者的练习: - )