Loops in ABAP are defined in a block of code that is executed several times.
The simplest form of loops consists of a code block surrounded by statements DO – ENDDO. Without further measures, these statements could establish an endless loop that must be avoided by one of the following possibilities:
- Specified Number of Loops
- By extending the DO statement with an integer expression followed by keyword TIMES, you can specify explicitly how often the code block is to be processed. The integer expression can be as simple as a number literal, but also arithmetic calculations can be used as well. If the value of the expression equals 0, the code block between DO and ENDDO is not executed at all, and the program immediately continues with the code after the ENDDO.
- Abort Based on a Logical Condition
- You can abort a loop anytime using the EXIT statement. The program then continues with the code after ENDDO. Be aware that outside of the loop EXIT has a different effect. There it terminates the processing of the current processing block, for example, the current method.
Usually, EXIT is surrounded by IF and ENDIF to terminate the loop depending on an abort condition. Be aware that such loops can turn into endless loops if the abort condition is never true.
Of course, it is possible to combine the two techniques, that is, explicitly specify the number of loops and then leave the loop with EXIT. Therefore, the number of loops becomes a maximum number that might not be reached at runtime.
In the code block between DO and ENDDO, you can implement read-accesses to ABAP built-in data object SY-INDEX. This integer variable serves as a loop counter, that is, the ABAP runtime increases the variable by one at the beginning of each new loop.
ABAP built-in variable SY-TABIX can fulfill a similar purpose for loops. But be aware that SY-TABIX is not really a counter, but it identifies the position of the table row that is processed in the current loop.