Loops

DO – ENDDO – Unconditional Loop
DO can be used to execute a certain lines of codes specific number of times.

DO 5 TIMES.
  WRITE sy-index.  " SY-INDEX (system variable) - Current loop pass
ENDDO.

Output
Loops-1

WHILE ENDWHILE – Conditional Loop

WHILE can be used to execute a certain lines of codes as long as the condition is true.

WHILE sy-index < 3.
  WRITE sy-index.
ENDWHILE.

Output
Loops-2

CONTINUE – Terminate a loop pass unconditionally.

After continue the control directly goes to the end statement of the current loop pass ignoring the remaining statements in the current loop pass, starts the next loop pass.

DO 5 TIMES.
  IF sy-index = 2.
    CONTINUE.
  ENDIF.
  WRITE sy-index.
ENDDO.

Output
Loops-3

CHECK – Terminate a loop pass conditionally.

If the condition is false, the control directly goes to the end statement of the current loop pass ignoring the remaining statements in the current loop pass, starts the next loop pass.

DO 5 TIMES.
  CHECK sy-index < 3.
  WRITE sy-index.
ENDDO.

Output
Loops-4

EXIT – Terminate an entire loop pass unconditionally.

After EXIT statement the control goes to the next statement after the end of loop statement.

DO 10 TIMES.
  IF sy-index = 2.
    EXIT.
  ENDIF.
  WRITE sy-index.
ENDDO.

Output

Loops-5


6 Comments

  1. I found your blog on google and read a few of your other posts. I just added you to my Google News Reader. Keep up the good work Look forward to reading more from you in the future.

    • SY-INDEX contains the current iteration number. Inside the inner loop, SY-INDEX contains current iteration number of inner loop. Once the ENDDO of inner loop is executed the SY-INDEX contains the value it had before entering the inner loop i.e. the current iteration number of outer loop.

      Try this.


      DO 2 TIMES.
      WRITE SY-INDEX.
      DO 5 TIMES.
      WRITE SY-INDEX.
      ENDDO.
      ENDDO.

Leave a Reply

Your email address will not be published.


*