Simple Loop with PERFORM
Introduction to Looping in COBOL
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.
What You'll Learn
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:
- The basic syntax of the
PERFORMstatement. - How to implement a loop that iterates a specified number of times.
- How to use the loop counter to control the iteration.
Here's a snippet of COBOL code to illustrate a simple loop using the PERFORM statement:
In the example provided:
- Initialization: The loop starts with
Counterset to 1. - Condition Check: The loop continues to run until
Counteris greater than 5. - Iteration: In each iteration of the loop,
Counteris incremented by 1. - Action: Within the loop, the current value of
Counteris 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:
Why It Matters
