Types of Loops in ABAP
1. WHILE Loop
The WHILE loop keeps running as long as a specific condition remains true. It checks the condition before each iteration.
Syntax:
WHILE counter <= 10.
WRITE: / counter.
Add 1 to counter.
ENDWHILE.
In this example, the loop continues to iterate as long as the counter variable remains less than or equal to 10. The loop prints values ranging from 1 to 10.
2. Do Loop
The Do loop is designed to execute at least once and then checks a condition to determine whether it should continue iterating. The condition is checked after each iteration.
DO.
WRITE: / counter.
ADD 1 TO counter.
IF counter > 10.
EXIT.
ENDIF.ENDDO.
This example prints values from 1 to 10, and the loop exits when the counter exceeds 10.
3. Nested Loops
Nested loops are a valuable tool when you need to iterate within another loop. They come in handy for processing hierarchical data or performing intricate operations.
DO 3 TIMES.
DO 2 TIMES.
WRITE: / sy-index, sy-index1.
ENDDO.
ENDDO.
In this code snippet, there is a nested loop structure called a Do loop. The outer loop iterates three times, and for each outer iteration, the inner loop iterates twice. This results in a total of six iterations overall.