PERFORM UNTIL
PERFORM UNTIL
- PERFORM...UNTIL statement is used to execute a statement block repetitively until a specific condition is TRUE.
- The variables used in this perform condition should be initialized, incremented, or decremented separately (outside of perform).
- Control passes to the following executable statements next to the PERFORM once the loop is completed.
- PERFORM UNTIL statement is both inline and outline.
- It's similar to a "do-while" or "repeat-until" loop in other programming languages.
Syntax -
Inline PEFORM...UNTIL | Outline PEFORM...UNTIL |
---|---|
|
|
Note! All statements coded in [ ] are optional. Either WITH TEST BEFORE or WITH TEST AFTER should be coded with PERFORM.
Parameters -
- paragraph-1 - The starting paragraph to be executed.
- THRU paragraph-2 - (Optional) If coded, indicates the end of a range of paragraphs to be executed. After executing this ending paragraph, control returns to the start of the range until the coded condition is true.
- condition - The condition that determines when the loop should terminate. The loop will continue as long as this condition is false. Once the condition becomes true, the loop terminates, and control passes to the statement following the PERFORM.
- WITH TEST BEFORE - tests the condition before executing the statements block. It is default with PERFORM if not coded any.
- WITH TEST AFTER - tests the condition after executing the statements block.
Practical Examples -
Scenario1 - Displaying loop iterations using inline PERFORM...UNTIL (PERFORM WITH TEST BEFORE...UNTIL).
Code -
----+----1----+----2----+----3----+----4----+
...
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-I PIC 9(01) VALUE 1.
PROCEDURE DIVISION.
DISPLAY "Before Inline PERFORM...UNTIL".
PERFORM UNTIL WS-I = 1
DISPLAY "Iteration: " WS-I
END-PERFORM.
DISPLAY "After Inline PERFORM...UNTIL".
...
OUTPUT -
Before Inline PERFORM...UNTIL After Inline PERFORM...UNTIL
Explaining Example -
In the above example, first, the condition is validated. If the condition returns true, the loop terminates and continues with executing the program flow.
Scenario2 - Displaying loop iterations using inline PERFORM WITH TEST AFTER...UNTIL.
Code -
----+----1----+----2----+----3----+----4----+
...
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-I PIC 9(01) VALUE 1.
PROCEDURE DIVISION.
DISPLAY "Before Inline PERFORM WITH TEST AFTER UNTIL".
PERFORM WITH TEST AFTER UNTIL WS-I = 1
DISPLAY "Iteration: " WS-I
END-PERFORM.
DISPLAY "After Inline PERFORM WITH TEST AFTER UNTIL".
...
OUTPUT -
Before Inline PERFORM WITH TEST AFTER UNTIL Iteration: 1 After Inline PERFORM WITH TEST AFTER UNTIL
Explaining Example -
In the above example, the statements in the loop get executed once, and then the condition is validated. So, we have a display "Iteration: " once even though the condition is true for the first time.