Summary: in this tutorial, you will learn how to use the ABAP do
statement to carry an unconditional loop.
Introduction to the ABAP do loop statement
The do
statement allows you to execute a code block in a specified number of times. The following illustrates the syntax of the do
statement:
do [n times]
[code_block]
enddo.
The n times
limits the number of iterations in a do
loop. The n
can be a literal number like 1, 2, 3,… or a numeric expression of type i
. If n
is less than or equal to 0
, the code_block
will not execute at all.
The n times
is optional. If you omit it, you need to terminate the loop by the exit
statement in the code_block
. Otherwise, the loop executes endlessly until the runtime environment terminates it.
Within the code_block
, you can access the system field sy-index
that stores the number of loops has been passed, which include both previous and the current iterations.
Typically, you use the do
statement to fill an internal table with data or to construct values.
ABAP do
example
The following example uses the do loop to calculate and shows the first five square numbers:
data gv_square type i.
do 5 times.
gv_square = ipow( base = sy-index exp = 2 ).
write: / sy-index, gv_square.
enddo.
Output:
1 1
2 4
3 9
4 16
5 25
How it works.
- The loop executes 5 times.
- In each iteration, use ipow to calculate a square number of the current sy-index and output the result to the screen.
Summary
- Use the ABAP
do
loop statement to carry an unconditional loop.