Welcome back! In our journey with COBOL so far, you've learned about simple loops using PERFORM
. In this lesson, we will expand on the PERFORM
statement by exploring more advanced loop constructs. Understanding these concepts will enable you to create more efficient and flexible loops, essential for handling complex tasks in your programs.
In this session, you'll delve deeper into the PERFORM
statement to understand how to control loops more effectively. Specifically, you will:
PERFORM UNTIL
construct.Consider the following snippet of COBOL code:
cobol1IDENTIFICATION DIVISION. 2PROGRAM-ID. PerformUntilSimpleDemo. 3 4DATA DIVISION. 5WORKING-STORAGE SECTION. 601 COUNTER PIC 9(2) VALUE 1. 7 8PROCEDURE DIVISION. 9 PERFORM UNTIL COUNTER > 5 10 DISPLAY 'Counter value: ' COUNTER 11 ADD 1 TO COUNTER 12 END-PERFORM 13 STOP RUN.
This code demonstrates how to create a loop that continues running until a certain condition is met, in this case, until COUNTER
exceeds 5. The output of the code will be:
Plain text1Counter value: 01 2Counter value: 02 3Counter value: 03 4Counter value: 04 5Counter value: 05
Let's break down the code to understand its key components:
COUNTER
starts with an initial value of 1.PERFORM UNTIL
statement ensures that the loop will keep executing until COUNTER
becomes greater than 5.COUNTER
is displayed.COUNTER
is incremented by 1 in each iteration. Notice that we achieve that using the ADD 1 TO COUNTER
statement, which is missing the GIVING
clause. This is a shorthand way of incrementing the value of COUNTER
by 1.COUNTER
exceeds 5, the loop terminates, and the program stops.Understanding each of these components will allow you to employ similar constructs in your programs, making them more efficient and easier to manage.
Mastering advanced loop constructs with the PERFORM
statement offers several advantages:
Ready to get started with hands-on practice? Let's move on to the practice section and enhance your loop-handling skills in COBOL!