Google Search - Blog...........

LOOPING statements in abap

Looping with DO statement

If you want to write your name say for 10 times, you need to write WRITE statement for 10 times.
When you want to process a statement more than once, you can write this statement within a loop with the DO statement as follows:

Syntax

DO 5 times.
Write : / name.
ENDDO.

The system continues processing the statement block for 5 times introduced by DO and concluded by ENDDO.

The system field SY-INDEX contains the number of times the loop has been processed so in this case when the loop is over value of sy-index will be 5.

In this case you know that, you want to perform WRITE statement for 5 times. But that is not the case always. Many times you need to terminate the loop depending upon certain conditions. This can be done, by using EXIT or STOP statement.

The important point to remember when you don’t you use TIMES option, is to avoid endless loops when working with the DO statement. If you do not use the TIMES option, include at least one EXIT, STOP statement so that the system can leave the loop.

EXIT and STOP takes you out of that loop.

Looping with WHILE Statement

If you want to process a statement block more than once as long as a condition is true, you can program a loop with the WHILE statement as follows:

Syntax
DATA: M TYPE I VALUE 0.
WHILE M < 10.
WRITE: / M.
M = M + 1.
ENDWHILE.

The system continues processing the statement block introduced by WHILE and concluded by ENDWHILE statements as long as M is less than 10 or until the system finds an EXIT, STOP.

The system field SY-INDEX contains the number of times the loop has been processed.

You can nest WHILE loops any number of times and also combine them with other loops.

Difference between DO loop and WHILE is that in WHILE, condition is checked first and if condition is true then loop is executed while in DO loop, the loop gets executed first if you don’t have TIMES option and then the condition is checked (if you have any).

You can have nested DO and WHILE or DO and IF or IF and IF or any possible situation.

No comments:

Post a Comment