Welcome back! In the previous lessons, you learned how to create decision paths using IF
statements and EVALUATE
statements in COBOL. You also explored how to use the PERFORM
statement to create loops. Now, we will elevate your coding skills by combining these two powerful concepts: conditional logic and loops.
Understanding how to integrate IF
statements within PERFORM
loops will help you create more dynamic and responsive COBOL programs. This skill is crucial, especially for applications in the banking industry, where multiple conditions and iterations often occur.
In this lesson, you'll learn how to create loops with embedded conditional logic using the PERFORM
statement. Specifically, you will:
PERFORM
with loops and IF
statements.Here's a snippet of COBOL code demonstrating the combination of loop and conditional logic:
cobol1IDENTIFICATION DIVISION. 2PROGRAM-ID. PerformWithIfDemo. 3DATA DIVISION. 4WORKING-STORAGE SECTION. 5 601 WS-INDEX PIC 99 VALUE 1. 701 WS-REMAINDER PIC 9. 801 WS-TEMP PIC 99. 9 10PROCEDURE DIVISION. 11 PERFORM VARYING WS-INDEX FROM 1 BY 1 UNTIL WS-INDEX > 10 12 DIVIDE WS-INDEX BY 2 GIVING WS-TEMP REMAINDER WS-REMAINDER 13 IF WS-REMAINDER = 0 THEN 14 DISPLAY "Number " WS-INDEX " is EVEN" 15 ELSE 16 DISPLAY "Number " WS-INDEX " is ODD" 17 END-IF 18 END-PERFORM 19 STOP RUN.
Note that here we use PIC 99
, which is another way to define a variable as a two-digit number using PIC 9(2)
.
In the provided example:
WS-INDEX
set to 1.WS-INDEX
is greater than 10.WS-INDEX
is incremented by 1.WS-INDEX
is even or odd by dividing it by 2 and examining the remainder.WS-INDEX
is even or odd.This example illustrates how you can perform different actions based on conditions within a loop, making your programs more versatile and efficient.
Combining loops with conditional logic offers several key benefits:
Excited to dive deeper? Let’s move on to the practice section and master combining conditional logic with loops in COBOL!