ABAP while

Summary: in this tutorial, you will learn how to use the ABAP while statement to perform a conditional loop.

Introduction to ABAP while loop

The while loop statement executes a code block as long as a condition is true. The following shows the syntax of the while statement:

while logical_expression.
   [code_block]
endwhile.

In this syntax, the while loop evaluates the logical_expression first. If the result is true, the loop is entered.

Inside the code_block, you need to change some variables to make the logical_expression false at some points. Otherwise, you will have an indefinite loop that will execute endlessly until it is terminated by the runtime environment.

If the logical_expression evaluates to false, the processing continues after the endwhile, no iteration is executed.

Before each new iteration, the while loop evaluates the logical expression again to determine whether to execute the next iteration.

Because the while loop evaluates the condition before each iteration, the while loop is often called a pretest loop.

Similar other loop statements such as do, you can access the system variable sy-index that stores the current loop index.

ABAP while loop example

The following example shows how to use the ABAP while loop:

data gv_counter type i value 5.

while gv_counter > 0.
  write: / 'Counter: ', gv_counter,
           'Iteration:', sy-index.
  gv_counter = gv_counter - 1.
endwhile.

Output:

Counter:           5  Iteration:          1
Counter:           4  Iteration:          2
Counter:           3  Iteration:          3
Counter:           2  Iteration:          4
Counter:           1  Iteration:          5

How it works.

  • First, declare and initialize the gv_counter to 5.
  • Then, use the while loop to check if gv_counter is greater than zero and execute the code that output the gv_counter and the current loop index (sy-index) to the screen. In each iteration, decrease the gv_counter by 1.

Summary

  • Use the while loop statement to execute a code block as long as a condition is true.