loop in assembly language

In high-level languages, it is often necessary to traverse some arrays or lists. We can use for loops, while loops, and do-while loops for convenient operations. In some practical problems, loop instructions are often used to solve problems that require continuous repetition.

There are three main components in the cycle program: initialization part, cycle body and cycle control part. The initialization part is for initialization and setting. The loop body is simply the part of the program that needs to be executed repeatedly, and the loop control part is the part that decides whether the loop needs to continue to execute.

For example, execute the loop performed by the while loop:

  The flow chart of do-while is as follows:

 In assembly language, the CPU executes the loop instruction in two steps, the first is (cx)=(cx)-1, the second step is to judge whether cx is 0, if cx is 0, then end the loop, if cx is not If it is 0, continue to the next cycle.

For example, we use assembly language to calculate the 10th power of 2, the code is as follows:

assume cs:code
code segment
   start:mov ax,2
      mov cx,10
    s:add ax,ax
      loop s
      
      mov ax,4c00h
      int 21h
code ends
end start

When executing the loop body s, when the initial situation is (cx)=10, (ax)=2, when performing a cycle, the (cx)=(cx)-1 and add ax,ax operations are executed, when At the end of the first cycle, (cx)=9, (ax)=4; when the second cycle is performed, (cx)=(cx)-1 and add ax, ax operations are performed, when the second cycle At the end of the loop, (cx)=8, (ax)=8;...When the tenth loop is executed, (cx)=(cx)-1 and add ax,ax operations are executed, at this time (cx) =0, (ax)=1024, at this time, the value of cx is 0, and the loop ends.

Guess you like

Origin blog.csdn.net/qq_54186956/article/details/126126730