Welcome back! Now that you've mastered working with nested IF
statements, it's time to explore another fundamental control structure: loops. Specifically, we'll delve into how to use the PERFORM
statement for creating loops in COBOL. Looping allows you to execute a block of code multiple times, which is crucial for tasks like processing arrays or performing repetitive operations.
In this lesson, you'll gain a solid understanding of how to create a simple loop using the PERFORM
statement in COBOL. You'll learn:
PERFORM
statement.Here's a snippet of COBOL code to illustrate a simple loop using the PERFORM
statement:
cobol1IDENTIFICATION DIVISION. 2PROGRAM-ID. PerformLoopDemo. 3DATA DIVISION. 4WORKING-STORAGE SECTION. 501 Counter PIC 9(2) VALUE 1. 6PROCEDURE DIVISION. 7 PERFORM VARYING Counter FROM 1 BY 1 UNTIL Counter > 5 8 DISPLAY "Counter: " Counter 9 END-PERFORM. 10 STOP RUN.
In the example provided:
Counter
set to 1.Counter
is greater than 5.Counter
is incremented by 1.Counter
is displayed.Note, that the Counter FROM 1
clause specifies the initial value of the loop counter, and BY 1
indicates the increment value. The loop continues until the condition Counter > 5
is met.
This simple loop executes the DISPLAY
statement five times, printing the values from 1 to 5. Notice that the DISPLAY
statement does not have a period at the end. We had a similar case with nested IF
statements. Here, as well, the period terminates the PERFORM
loop prematurely. In COBOL, a period indicates the end of a logical block. When used inside a PERFORM
loop, it signifies that the loop should stop executing after the first iteration because the period effectively ends the entire loop block.
Understanding how to set up and control loops is essential for performing repetitive tasks.
The output of the program will look as follows:
Plain text1Counter: 01 2Counter: 02 3Counter: 03 4Counter: 04 5Counter: 05
Looping structures are indispensable in programming for several reasons:
Imagine you are developing a banking application that needs to process multiple account transactions. Using loops, you can efficiently handle each transaction in turn, making your application both powerful and manageable.
Ready to master the use of loops in COBOL? Let's proceed to the practice section and start building loops together!