Summary -

In this topic, we described about the below sections -

WHILE loop executes the block of statements until the specified condition is false. The block of statements can gets executed any number of times as long as the condition is true. In while loop, condition is validated before executing the block of statements. If the condition is false for the first time, no statements in the loop gets executed.

The block of statements is either a single statement or multiple statements. The block of statements coded in between WHILE and ENDWHILE statements. ENDWHILE statement is mandatory with WHILE loop. All the statements should be ended with period (.) including WHILE and ENDWHILE.

Syntax -

WHILE <logical-expression/Condition> 
		[ VARY <condition-variable> FROM <initial-value> 
		NEXT <increment-value>].

  • logical-expression/Condition - Specifies the condition that used to validate to execute the statements-block-1
  • condition-variable - Specifies the variable that is used in the loop validation.
  • initial-value - Specifies the condition-variable initial value.
  • increment-value - Specifies the incrementing value for every loop.

Below diagram decribes the flow of WHILE loop -

While Loop Flow Diagram

WHILE loop validates the condition before executing the set of statements. If the condition is true, then the Statements-block1 gets executed. After statements-block1 execution completed, control transfer to WHILE loop to validate the condition again. If the condition is true, then statements-block1 gets executed. This process iterates until the condition is false.

Once the condition determined as false, loop gets terminated and control transferred to statements-block2.

Example -

Below example shows how the WHILE loop coded in the application program.

Code -

*& Report  Z_WHILE_LOOP
*& Written by TutorialsCampus


* Declaring Variables

* Iterating loop 9 times
WHILE W_I < 10.

* Displaying the Iteration number
  WRITE : /'Iteration ',W_I.

* Adding 1 to iteration number
  W_I = W_I + 1.


Output -

While Loop 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.

WHILE W_I < 10.. ENDWHILE, iterates the set of statements until the W_I equal to 10. i.e., loop executes 9 (from 1 to 9) times.

W_I = W_I + 1, adds 1 to W_I that increases the looping number to get equal for 10. If W_I = W_I + 1 statement is missed in the loop, loop executes infinite times because the condition never gets satisfied as no increase in W_I value.