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 PERFORM statement.
  • 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:

IDENTIFICATION DIVISION.
PROGRAM-ID. PerformLoopDemo.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Counter PIC 9(2) VALUE 1.
PROCEDURE DIVISION.
    PERFORM VARYING Counter FROM 1 BY 1 UNTIL Counter > 5
        DISPLAY "Counter: " Counter
    END-PERFORM.
    STOP RUN.

In the example provided:

  1. Initialization: The loop starts with Counter set to 1.
  2. Condition Check: The loop continues to run until Counter is greater than 5.
  3. Iteration: In each iteration of the loop, Counter is incremented by 1.
  4. Action: Within the loop, the current value of 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:

Counter: 01
Counter: 02
Counter: 03
Counter: 04
Counter: 05

Why It Matters

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal