SAP ABAP - Nested Loop



The DO and WHILE statements can be tested as well as combined with other loop forms. Each nested loop will have it’s own SY-INDEX created and monitored by the system.

Syntax

The syntax for nested DO loop is −

DO [n TIMES]. 
<statement block n>. 
   DO [m TIMES]. 
   <statement block m>. 
   ENDDO. 
ENDDO.

Example

REPORT YS_SEP_15.
  
Data: a1 type I, b1 type I.
  
a1 = 0.  
b1 = 0.
  
Do 2 times.
  
a1 = a1 + 1.
  
Write: /'Outer', a1.
  
Do 10 times.  
b1 = b1 + 1.
  
Write: /'Inner', b1.
  
ENDDo. 
ENDDo

The above code produces the following output −

Outer   1 
Inner   1 
Inner   2 
Inner   3 
Inner   4 
Inner   5 
Inner   6 
Inner   7 
Inner   8 
Inner   9 
Inner  10 
Outer   2 
Inner  11 
Inner  12 
Inner  13 
Inner  14 
Inner  15 
Inner  16 
Inner  17 
Inner  18 
Inner  19 
Inner  20

In this example, the outer DO loop is processed twice and the inner DO loop is processed 10 times, each time the outer DO loop is processed. So in this case, the inner loop is processed 20 times.

sap_abap_loop_control.htm
Advertisements