Summary -

In this topic, we described about the below sections -

EXIT statement terminates the loop completely and transfers control to the statement block immediately after the loop. EXIT statement can be used as conditional or unconditional based on the requirement/usage.

Normally EXIT statement comes up with a condition. If the EXIT statement is executed, the loop gets terminated immediately or unconditionally.

If EXIT statement coded without condition, then the loop gets terminated in the first iteration itself. EXIT statement can terminate the loop and can't bypass the statements. EXIT should be ended with period (.).

Syntax -

EXIT.

Below diagram decribes the flowchart of EXIT statement -

Exit Statement Flow Diagram

  • Looping condition - Specifies the condition with loop statement(DO/WHILE).

Execution process -

Step1 - If the looping condition is true, then EXIT condition(if existed) gets validated.

Step2 - If EXIT condition is true, EXIT gets executed. Loop gets terminated immediately and control transfers to statements-block3.

Step3 - If EXIT condition is false, statements-block1 gets executed and control transfers to validate looping condition again.

Step4 - step-1 to step-3 gets executed repeatedly until the looping condition is false.

Step5 - If looping condition is false, statements-block3 gets executed and control transfers to next executable statements if any.


Example -

Below example shows how the EXIT statement coded in the application program.


Code -

*&---------------------------------------------------------------------*
*& Report  Z_EXIT
*&---------------------------------------------------------------------*
*& Written by TutorialsCampus
*&---------------------------------------------------------------------*

REPORT  Z_EXIT.

* Declaring Variable
DATA: W_I TYPE I VALUE 0.

* DO loop iterates 10 times
DO 10 TIMES.

* incrementing Iteration number
  W_I = W_I + 1.

* Breaks the loop when iteration equals to 5.
  IF W_I EQ 5.
    EXIT.
  ENDIF.

* Displays Iteration number
  WRITE : /'Iteration ',W_I.

ENDDO.

Output -

Exit Statement Example Output

Explaining Example -

In the above example, each and every statement is preceeded with a comment to explain about the statement. Go through them to get clear understanding of example code.

DO 10 TIMES, iterates loop 10 times. W_I = W_I + 1, used to display the iteration number for understanding and have no impact on loop iteration.

W_I EQ 5 condition satisfies, EXIT gets executed. Once EXIT executed, it breaks the loop and control passes to next statements after the DO loop.