The IF statement is COBOL's primary conditional construct, enabling decision-making based on conditions. It evaluates whether a condition is true or false and executes the appropriate code path.
12345678910111213141516171819*> Simple IF statement IF condition statement-1 statement-2 END-IF *> IF with ELSE IF condition statements (when true) ELSE statements (when false) END-IF *> Multiple conditions with logical operators IF condition-1 AND condition-2 statements ELSE statements END-IF
= or EQUAL TO - EqualNOT = or NOT EQUAL TO - Not equal> or GREATER THAN - Greater than< or LESS THAN - Less than>= - Greater than or equal<= - Less than or equal12345678910111213141516171819*> AND - both conditions must be true IF field-1 > 0 AND field-2 NOT = SPACES PERFORM PROCESS-DATA END-IF *> OR - either condition can be true IF department = "IT" OR department = "ENGINEERING" MOVE "TECH" TO category END-IF *> NOT - negates the condition IF NOT end-of-file PERFORM READ-NEXT-RECORD END-IF *> Complex combinations with parentheses IF (salary > 50000 AND years > 5) OR (rating = "EXCELLENT") PERFORM AWARD-BONUS END-IF
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253IDENTIFICATION DIVISION. PROGRAM-ID. IF-EXAMPLES. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-AMOUNT PIC 9(5)V99 VALUE 1234.56. 01 WS-RATE PIC 9V999 VALUE 0.15. 01 WS-DISCOUNT PIC 9(5)V99. 01 WS-CUSTOMER PIC X(20). 88 VIP-CUSTOMER VALUE "PREMIUM", "GOLD". 01 WS-QUANTITY PIC 9(3) VALUE 50. PROCEDURE DIVISION. MAIN-LOGIC. *> Simple comparison IF WS-AMOUNT > 1000 COMPUTE WS-DISCOUNT = WS-AMOUNT * WS-RATE DISPLAY "Discount applied: " WS-DISCOUNT END-IF *> IF-ELSE structure IF VIP-CUSTOMER DISPLAY "VIP customer - special treatment" COMPUTE WS-DISCOUNT = WS-AMOUNT * 0.20 ELSE DISPLAY "Regular customer" COMPUTE WS-DISCOUNT = WS-AMOUNT * 0.10 END-IF *> Nested IF statements IF WS-QUANTITY > 100 IF VIP-CUSTOMER COMPUTE WS-DISCOUNT = WS-AMOUNT * 0.30 ELSE COMPUTE WS-DISCOUNT = WS-AMOUNT * 0.15 END-IF ELSE IF VIP-CUSTOMER COMPUTE WS-DISCOUNT = WS-AMOUNT * 0.20 ELSE COMPUTE WS-DISCOUNT = WS-AMOUNT * 0.10 END-IF END-IF *> Multiple conditions with logical operators IF WS-AMOUNT > 1000 AND WS-QUANTITY > 50 DISPLAY "Bulk order discount eligible" ELSE IF WS-AMOUNT > 500 OR VIP-CUSTOMER DISPLAY "Standard discount eligible" END-IF END-IF STOP RUN.
Explain It Like I'm 5 Years Old:
Think of an IF statement like making decisions! If you're deciding whether to play outside, you might say "IF it's sunny outside, THEN I'll go play in the park, ELSE I'll stay inside and read." Just like that, COBOL programs use IF to make choices. The program checks if something is true (like sunny weather) and does one thing, or if it's false (rainy) and does something different. It's like the computer asking questions and doing different things based on the answers!