BudiBadu Logo
Samplebadu

COBOL by Example: Sections

COBOL 2002

Organizing procedural code using sections within the PROCEDURE DIVISION as logical groupings of paragraphs, implementing the PERFORM statement to transfer control between sections and return after completion, structuring programs into modular units like initialization, processing, and cleanup, and preventing fall-through execution with proper control flow management using STOP RUN.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. SECTIONS-DEMO.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  NUM1 PIC 99 VALUE 10.
       
       PROCEDURE DIVISION.
       MAIN-LOGIC SECTION.
           DISPLAY "In Main Logic Section".
           PERFORM CALCULATION-SECTION.
           STOP RUN.
           
       CALCULATION-SECTION.
           ADD 5 TO NUM1.
           DISPLAY "Result: " NUM1.

Explanation

In the Procedure Division, code can be organized into SECTIONS. A section is a collection of one or more paragraphs. Sections provide a higher level of grouping than paragraphs, allowing you to modularize your code into logical units like initialization, processing, and cleanup sections.

The PERFORM statement is used to transfer control to a section (or paragraph) and return when it completes. This is similar to calling a void function in other languages. In this code example, when you PERFORM CALCULATION-SECTION, the program jumps to that section, executes all instructions within it, and then returns to the line immediately following the PERFORM statement.

Using sections is considered a best practice for structuring large COBOL programs. It makes the code easier to read and navigate. A section ends when the next section begins, or at the end of the program. It is important to manage control flow carefully (e.g., using STOP RUN) to prevent the program from accidentally falling through into the next section.

Code Breakdown

9
MAIN-LOGIC SECTION. This label defines the start of the main section. Execution begins here because it's the first code in the Procedure Division.
11
PERFORM CALCULATION-SECTION. This command temporarily transfers control to the CALCULATION-SECTION. After that section finishes, control returns here.
12
STOP RUN. This is critical. Without it, the program would continue executing line by line and "fall through" into CALCULATION-SECTION again, running it a second time.
14
CALCULATION-SECTION. The start of the second section. It contains the logic for our calculation.
15
ADD 5 TO NUM1. A simple arithmetic operation. It adds 5 to the current value of NUM1 (which started at 10) and stores the result (15) back in NUM1.