DO and WHILE loops in ABAP

DO and WHILE statements are used for creating loops in ABAP programming. There are mainly four types of loops in ABAP programs, they are

  • Loops with DO statement (Mainly for unconditional loops)
  • Loops with WHILE statement (Mainly for conditional loops)
  • Loops with LOOP statement (Looping in Internal tables)
  • Loops with SELECT statement (Looping through the database data)

Here we are going to learn about the loops with DO and WHILE statements.

DO loops

DO statement is used for creating unconditional loops.

Syntax

DO [<n> TIMES] [VARYING <f> FROM <f1> NEXT <f2>].

…..

ENDDO

 

  • TIMES addition is used for specifying the number of loop iterations. If we are not specifying this additions, we should use EXIT or STOP like loop terminating statements to avoid endless looping.
  • VARYING addition is used for specifying the distance between the fields for iteration.
  • DO statement blocks should always end with ENDDO statement.

Sample program with DO statement

DO 10 TIMES.

WRITE SY-INDEX.

ENDDO.

 

WHILE loops

WHILE statement is used for creating conditional loops. As long as the specified condition is TRUE the loop iterations will continue. When the condition becomes FALSE the loop will be terminated.

Syntax

WHILE <condition> [VARY <f> FROM <f1> NEXT <f 2>].

….

ENDWHILE.

 

  • The loops with WHILE statement will continue as long as the condition becomes false or any terminating statements like EXIT or STOP is triggered in the block statements.
  • VARY addition is same as VARYING addition for do loops, for specifying the distance between the fields.
  • WHILE statement blocks should always end with ENDWHILE statement.
Also Read : View Other ABAP Keywords & Syntax -> ABAP Transaction codes