do while loops arrange execution of a loop consisting of any number of statements when the number of iterations is not known beforehand. The body of the loop will be executed at least once. The loop exits when a certain logical condition becomes false.
In C++, the do while loop has the following form:
do { <statements> } while <condition>
Write some code for computing the sum of the first four elements of an integer array. Let the number of its elements be seven. To implement this task, use the following variables :
x1 ”an integer array of seven elements
Ix1 ”the index of the current element of the array
Sumx1 ”the current total value
A fragment of the C++ code shown in Listing 4.7 is quite simple.
... int X1[7] = {2, 4, 5, 1, 1, 9, 3}; int IX1 = 0; int sumX1 = 0; do { sumX1 = sumX1 + X1[1X1]; IX1++; } while (IX1 <= 3); ...
An assembly variant of the do while loop is shown in Listing 4.8.
.686 .model flat .data X1 DD 2, 2 3, 5, 9, 1, 9, 3 SX1 DD $X1 IX1 DD 1 CNT EQU 3 SUMX1 DD 0 .code start: push EBX mov EBX, offset X1 mov EAX, 0 mov EDX, DWORD PTR SX1 shr EDX, 2 cmp EDX, CNT jl EXIT NEXT: add EAX, [EBX] cmp DWORD PTR 1X1, CNT jg EXIT inc DWORD PTR 1X1 add EBX, 4 jmp NEXT EXIT: mov DWORD PTR SUMX1, EAX pop EBX . . . end start
First, all necessary variables are initialized . To access the elements of the array, its address is put to the EBX register:
mov EBX, offset X1
The initial total value equal to zero is put to the EAX register:
mov EAX, 0
The condition of the do while loop is checked in the assembly code with the following command:
cmp DWORD PTR IX1, CNT
where IX1 is the current array index.
Since an integer value of an array element takes a double word in the memory, to access the next element, you should increase the address value by four, just like in the previous example:
add EBX, 4
The result is put to the SUMX1 variable for later use.