WHILE ( SAP ABAP Keyword)

WHILE is a keyword used in SAP ABAP programming.This tutorial covers its introduction & syntax details.

WHILE

Basic form
WHILE logexp.

 

Addition

… VARY f FROM f1 NEXT f2.

Effect
Repeats the processing enclosed between the WHILE and ENDWHILE statements as long as the logical expression logexp is true.

Checks the condition before each loop pass. If it is no longer true, processing resumes after ENDWHILE .

You can use the CONTINUE statement to leave the current loop pass prematurely and skip to the next loop pass.

Example

DATA: SEARCH_ME TYPE I,
MIN TYPE I VALUE 0,
MAX TYPE I VALUE 1000,
TRIES TYPE I,
NUMBER TYPE I.
SEARCH_ME = 23.
WHILE NUMBER <> SEARCH_ME.
ADD 1 TO TRIES.
NUMBER = ( MIN + MAX ) / 2.
IF NUMBER > SEARCH_ME.
MAX = NUMBER – 1.
ELSE.
MIN = NUMBER + 1.
ENDIF.
ENDWHILE.

The
above code performs a (binary) search for the “unknown” number
SEARCH_ME which lies between MIN and MAX . TRIES contains the number of
attempts needed to find it.

Notes
WHILE loops can be nested any number of times within themselves and other loops.
The
termination condition and the processing you want to perform in the
loop should be well thought out beforehand, so as to avoid the
occurrence of endless loops.

Addition
… VARY f FROM f1 NEXT f2.

Effect
Varies the value of the field f during loop processing.

At
the start of each loop pass, f receives a new value. During the first
loop pass, f has the value of the field f1 ; on the second loop pass,
it has the value of the field f2 , and so on.

The difference
between the fields f1 and f2 determines the size of the step varying
the value of the variable f in all subsequent loop passes, i.e. it is
important that the fields you want to process within the loop have the
same distance between each other in memory (see also DO VARYING ).

If
the value of f changes when processing passes through the loop, the new
value is placed in the field fn just assigned (transfer type: by value
and result) at the end of the relevant loop pass. If the loop pass is
terminated by a dialog message, any changed value of f is not
transported back for this loop pass.

VARY can declare any number of variables.

Example

DATA: BEGIN OF WORD,
ONE VALUE ‘E’,
TWO VALUE ‘x’,
THREE VALUE ‘a’,
FOUR VALUE ‘m’,
FIVE VALUE ‘p’,
SIX VALUE ‘l’,
SEVEN VALUE ‘e’,
EIGHT VALUE ‘!’,
END OF WORD,
LETTER1, LETTER2.
WHILE LETTER2 <> ‘!’
VARY LETTER1 FROM WORD-ONE NEXT WORD-THREE
VARY LETTER2 FROM WORD-TWO NEXT WORD-FOUR.
WRITE: LETTER1, LETTER2.
ENDWHILE.

This code outputs the character string

” E x a m p l e !” .

Note
If
VARY fields (i.e. fields which are filled with a new value on every
loop pass) also occur in the WHILE condition, you must ensure that the
WHILE condition is evaluated first. Then, if the WHILE condition is
(still) true, the VARY fields can be reset.

More References