A for loop arranges execution of a statement or a group of statements for a particular number of times.
In its general form, the loop looks like this:
For (initialization expression; condition; modifier expression) <statements>
When a program encounters the loop, it executes the initialization expression, which sets the loop counter to the initial value. Then the so-called terminating condition is evaluated. The loop executes while this expression is true. Every time the loop body is executed, the modifier expression changes the loop counter. When the condition is false, the for loop terminates, and the statements that immediately follow it are executed.
In Visual C++, a for loop has a uniform syntax regardless of the direction of the modifier:
for (initialization expression; condition; modifier)
Most often, a for loop is used for iterative mathematical calculations with a constant increment and a known number of iterations, or it is used to search for elements in arrays or strings. Here, we will look at an example of using a for loop. Suppose you want to find the sum of the first seven elements of an array of 10 integers.
In C++ .NET, a fragment of the code could appear as shown in Listing 4.9.
... int i1[10] = {3, 5, 2, 7, 9, 1, 3, 7, 11, 15}; int isum = 0; for (int cnt = 0; cnt < 7; cnt++) { isum = isum + i1[cnt]; } ...
In assembler, it is convenient to implement a for loop with the loop command. In this case, the loop counter is put to the ECX register, and the current total is put to the EAX register. The address of the il integer array is put to the ESI register.
Before jumping to the next iteration, the address in ESI is increased by 4. After the loop terminates, the sum is stored in the isum variable.
The code fragment is shown in Listing 4.10.
.686 .model flat .data i1 DD 3, 5, 2 , 7, 9, 1, 3, 7, 11, 15 isum DD 0 .code start: mov ECX, 7 xor EAX, EAX lea ESI, DWORD PTR i1 next: add EAX, [ESI] add ESI, 4 loop next mov DWORD PTR isum, EAX ... end start