Conditional execution is a fundamental concept in programming that allows a program to make decisions and execute different code paths based on specific conditions. In COBOL, conditional execution is primarily implemented through the IF statement and various condition types that allow for sophisticated decision-making logic.
Structure | Purpose | Key Features |
---|---|---|
Simple IF | Basic condition testing | Execute statements only if condition is true |
IF-ELSE | Binary decision | Different actions for true and false conditions |
Nested IF | Multi-level decisions | Conditions within conditions |
EVALUATE | Multi-way branching | Case/switch-like structure with multiple conditions |
Conditional execution is essential for creating programs that can respond to different situations, process data according to business rules, and handle exceptions. A solid understanding of COBOL's conditional structures and operators is crucial for writing effective business applications.
The IF statement is the primary means of implementing conditional logic in COBOL. It allows you to test conditions and execute specific statements based on whether those conditions are true or false.
Format 1: Simple IF
12345IF condition statement-1 statement-2 ... END-IF
Format 2: IF-ELSE
123456789IF condition statement-1 statement-2 ... ELSE statement-3 statement-4 ... END-IF
Format 3: Nested IF
1234567891011IF condition-1 statement-1 IF condition-2 statement-2 ELSE statement-3 END-IF statement-4 ELSE statement-5 END-IF
1234567891011121314151617181920212223242526272829303132333435363738394041424344* Example 1: Simple IF IF EMPLOYEE-SALARY > 50000 ADD 1 TO HIGH-SALARY-COUNT END-IF. * Example 2: IF-ELSE IF CUSTOMER-STATUS = "ACTIVE" PERFORM PROCESS-ACTIVE-CUSTOMER ELSE PERFORM PROCESS-INACTIVE-CUSTOMER END-IF. * Example 3: Multiple statements in IF/ELSE blocks IF ORDER-AMOUNT > 1000 MOVE "Y" TO DISCOUNT-FLAG COMPUTE DISCOUNT = ORDER-AMOUNT * 0.10 COMPUTE NET-AMOUNT = ORDER-AMOUNT - DISCOUNT ELSE MOVE "N" TO DISCOUNT-FLAG MOVE 0 TO DISCOUNT MOVE ORDER-AMOUNT TO NET-AMOUNT END-IF. * Example 4: Nested IF statements IF ACCOUNT-TYPE = "CHECKING" IF ACCOUNT-BALANCE < 1000 MOVE 10.00 TO SERVICE-CHARGE ELSE MOVE 0 TO SERVICE-CHARGE END-IF PERFORM PROCESS-CHECKING ELSE IF ACCOUNT-TYPE = "SAVINGS" IF ACCOUNT-BALANCE < 500 MOVE 5.00 TO SERVICE-CHARGE ELSE MOVE 0 TO SERVICE-CHARGE END-IF PERFORM PROCESS-SAVINGS ELSE MOVE "UNKNOWN ACCOUNT TYPE" TO ERROR-MESSAGE PERFORM PROCESS-ERROR END-IF END-IF.
Issue | Impact | Solution |
---|---|---|
Missing END-IF | Ambiguous scope, incorrect execution flow | Always use END-IF terminators |
Deeply nested IFs | Code becomes difficult to follow and maintain | Use EVALUATE or extract to separate paragraphs |
Missing ELSE clause | May not handle all possible cases | Include ELSE or document why it's intentionally omitted |
Complex conditions | Error-prone logic, hard to debug | Break down into simpler conditions, use 88-level items |
Relational conditions compare two operands using relational operators. They are the most common type of condition used in COBOL programs for comparing values and making decisions based on those comparisons.
Operator | Meaning | Example |
---|---|---|
IS EQUAL TO, = | Equal | IF A = B |
IS GREATER THAN, > | Greater than | IF A > B |
IS LESS THAN, < | Less than | IF A < B |
IS GREATER THAN OR EQUAL TO, >= | Greater than or equal | IF A >= B |
IS LESS THAN OR EQUAL TO, <= | Less than or equal | IF A <= B |
IS NOT EQUAL TO, <> | Not equal | IF A <> B |
Note: The word "IS" is optional in these operators and is often omitted.
123456789101112131415161718192021222324252627282930313233343536373839* Example 1: Basic comparisons IF EMPLOYEE-SALARY > 50000 ADD 1 TO HIGH-SALARY-COUNT END-IF. IF CUSTOMER-BALANCE < 0 PERFORM PROCESS-OVERDUE-ACCOUNT END-IF. IF ORDER-QUANTITY = 0 DISPLAY "Order quantity cannot be zero" MOVE "Y" TO ERROR-FLAG END-IF. * Example 2: Using the optional IS keyword IF ACCOUNT-STATUS IS EQUAL TO "CLOSED" PERFORM REJECT-TRANSACTION END-IF. * Example 3: Comparing with literals IF TRANSACTION-CODE = "ADD" PERFORM ADD-RECORD END-IF. IF ZIP-CODE >= "90000" AND ZIP-CODE <= "96199" MOVE "CALIFORNIA" TO STATE-NAME END-IF. * Example 4: Comparing numeric fields IF TOTAL-AMOUNT >= MIN-ORDER-AMOUNT MOVE "Y" TO VALID-ORDER ELSE MOVE "Order amount below minimum" TO ERROR-MESSAGE END-IF. * Example 5: Not equal condition IF RECORD-TYPE <> "HEADER" PERFORM PROCESS-DETAIL-RECORD END-IF.
Comparison Type | Description | Example |
---|---|---|
Numeric to numeric | Based on algebraic value | IF SALARY > THRESHOLD |
Numeric to numeric literal | Based on algebraic value | IF QUANTITY < 10 |
Alphanumeric to alphanumeric | Character-by-character | IF NAME = OTHER-NAME |
Alphanumeric to alphanumeric literal | Character-by-character | IF CODE = "ABC" |
Group to group | Treated as alphanumeric | IF RECORD-1 = RECORD-2 |
Class conditions test whether the data in a field belongs to a particular class of data, such as alphabetic or numeric. These conditions are useful for validating input data and ensuring that fields contain the expected type of data before processing.
Class Test | Description | Example |
---|---|---|
NUMERIC | Contains only digits (0-9) and possibly a sign | IF AMOUNT IS NUMERIC |
ALPHABETIC | Contains only letters (A-Z, a-z) and spaces | IF NAME IS ALPHABETIC |
ALPHABETIC-LOWER | Contains only lowercase letters (a-z) and spaces | IF FIELD IS ALPHABETIC-LOWER |
ALPHABETIC-UPPER | Contains only uppercase letters (A-Z) and spaces | IF FIELD IS ALPHABETIC-UPPER |
ALPHANUMERIC | Contains any character in the computer's character set | IF FIELD IS ALPHANUMERIC |
DBCS, KANJI (in some dialects) | Contains only valid double-byte characters | IF FIELD IS DBCS |
Note: The IS keyword is optional in these tests. NOT can be used to negate the test (e.g., IF FIELD IS NOT NUMERIC).
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647* Example 1: Validating numeric input IF CUSTOMER-ID IS NOT NUMERIC DISPLAY "Customer ID must contain only digits" MOVE "Y" TO ERROR-FLAG END-IF. * Example 2: Checking for valid names IF CUSTOMER-NAME IS NOT ALPHABETIC DISPLAY "Name must contain only letters and spaces" MOVE "Y" TO ERROR-FLAG END-IF. * Example 3: Validating zip code IF ZIP-CODE IS NOT NUMERIC DISPLAY "Zip code must contain only digits" MOVE "Y" TO ERROR-FLAG END-IF. * Example 4: Ensuring uppercase for a code IF PRODUCT-CODE IS NOT ALPHABETIC-UPPER DISPLAY "Product code must be uppercase letters only" MOVE "Y" TO ERROR-FLAG END-IF. * Example 5: Complete input validation VALIDATE-CUSTOMER-INPUT. MOVE "N" TO ERROR-FLAG. IF CUSTOMER-ID IS NOT NUMERIC DISPLAY "Error: Customer ID must be numeric" MOVE "Y" TO ERROR-FLAG END-IF. IF CUSTOMER-NAME IS NOT ALPHABETIC DISPLAY "Error: Name must contain only letters and spaces" MOVE "Y" TO ERROR-FLAG END-IF. IF POSTAL-CODE IS NOT NUMERIC DISPLAY "Error: Postal code must be numeric" MOVE "Y" TO ERROR-FLAG END-IF. IF ACCOUNT-TYPE IS NOT ALPHABETIC-UPPER DISPLAY "Error: Account type must be uppercase letters" MOVE "Y" TO ERROR-FLAG END-IF.
Scenario | Class Test | Example |
---|---|---|
User input validation | NUMERIC, ALPHABETIC | Ensuring phone numbers are numeric, names are alphabetic |
Data conversion preparation | NUMERIC | Checking if a field can be converted to a numeric value |
File record validation | Various | Validating data in imported files before processing |
Code format validation | ALPHABETIC-UPPER | Ensuring standardized codes are in correct format |
Sign conditions test whether the value of a numeric data item is positive, negative, or zero. These conditions provide a direct way to test the sign of a numeric item without explicitly comparing it to zero.
Sign Test | Description | Example |
---|---|---|
POSITIVE | Value is greater than zero | IF AMOUNT IS POSITIVE |
NEGATIVE | Value is less than zero | IF AMOUNT IS NEGATIVE |
ZERO | Value is exactly zero | IF AMOUNT IS ZERO |
Note: The IS keyword is optional. NOT can be used to negate the test (e.g., IF AMOUNT IS NOT POSITIVE).
12345678910111213141516171819202122232425262728293031323334353637383940414243444546* Example 1: Basic sign conditions IF BALANCE IS POSITIVE DISPLAY "Account in good standing" END-IF. IF AMOUNT IS NEGATIVE DISPLAY "Credit transaction" ELSE DISPLAY "Debit transaction" END-IF. IF QUANTITY IS ZERO DISPLAY "Item out of stock" END-IF. * Example 2: Using NOT with sign conditions IF BALANCE IS NOT POSITIVE DISPLAY "Account requires attention" PERFORM PROCESS-PROBLEM-ACCOUNT END-IF. * Example 3: Process based on balance sign EVALUATE TRUE WHEN BALANCE IS POSITIVE PERFORM PROCESS-POSITIVE-BALANCE WHEN BALANCE IS NEGATIVE PERFORM PROCESS-NEGATIVE-BALANCE WHEN BALANCE IS ZERO PERFORM PROCESS-ZERO-BALANCE END-EVALUATE. * Example 4: Complete account processing logic PROCESS-ACCOUNT. IF ACCOUNT-BALANCE IS POSITIVE IF ACCOUNT-BALANCE > MINIMUM-BALANCE PERFORM CALCULATE-INTEREST ELSE MOVE 0 TO INTEREST-AMOUNT END-IF ELSE IF ACCOUNT-BALANCE IS NEGATIVE PERFORM CALCULATE-PENALTY ELSE MOVE "ZERO BALANCE ACCOUNT" TO ACCOUNT-STATUS END-IF END-IF.
Feature | Sign Conditions | Relational Conditions |
---|---|---|
Syntax | IF amount IS POSITIVE | IF amount > 0 |
Readability | More explicit for sign tests | More versatile for general comparisons |
Functionality | Limited to sign testing | Can compare against any value |
Usage in code | Better communicates intent for sign testing | Better for specific value comparisons |
While both approaches produce the same result, sign conditions often make the code more readable when specifically testing for positive, negative, or zero values.
Complex conditions combine two or more conditions using logical operators AND, OR, and NOT. They allow you to express sophisticated business rules and decision logic in a single condition.
Operator | Description | Example |
---|---|---|
AND | Both conditions must be true | IF A > 0 AND B > 0 |
OR | At least one condition must be true | IF A = 1 OR A = 2 |
NOT | Negates a condition | IF NOT (A = B) |
1234567891011121314151617181920212223242526272829303132333435363738* Example 1: Using AND IF EMPLOYEE-AGE >= 18 AND EMPLOYEE-AGE <= 65 PERFORM PROCESS-ELIGIBLE-EMPLOYEE END-IF. * Example 2: Using OR IF PAYMENT-TYPE = "CREDIT" OR PAYMENT-TYPE = "DEBIT" PERFORM PROCESS-CARD-PAYMENT ELSE PERFORM PROCESS-CASH-PAYMENT END-IF. * Example 3: Using NOT IF NOT (ACCOUNT-STATUS = "ACTIVE") DISPLAY "Account is not active" PERFORM REJECT-TRANSACTION END-IF. * Example 4: Combining AND and OR IF (CUSTOMER-TYPE = "PREMIUM" OR CUSTOMER-TYPE = "GOLD") AND ORDER-AMOUNT > 1000 PERFORM APPLY-DISCOUNT END-IF. * Example 5: Multiple conditions with AND and OR IF (ACCOUNT-TYPE = "CHECKING" AND ACCOUNT-BALANCE < MINIMUM-BALANCE) OR (ACCOUNT-TYPE = "SAVINGS" AND ACCOUNT-BALANCE < SAVINGS-MINIMUM) PERFORM CHARGE-SERVICE-FEE END-IF. * Example 6: Complex business rule IF (EMPLOYEE-STATUS = "FULLTIME" AND YEARS-OF-SERVICE >= 5) OR (EMPLOYEE-STATUS = "PARTTIME" AND YEARS-OF-SERVICE >= 10) PERFORM CALCULATE-BONUS PERFORM UPDATE-EMPLOYEE-RECORD ELSE DISPLAY "Employee not eligible for bonus" END-IF.
To ensure clarity and avoid mistakes, it's recommended to use parentheses to explicitly specify the order of evaluation, even when not strictly necessary.
Logical Pattern | COBOL Expression | Example Use Case |
---|---|---|
Range check | A >= B AND A <= C | Age validation, date range check |
Multiple valid values | A = B OR A = C OR A = D | Status codes, transaction types |
Exclusion | NOT (A = B) | Skipping certain records |
Conditional qualification | (A = B AND C > D) OR (A = E AND C > F) | Tiered business rules |
Boolean flag check | FLAG-1 = "Y" AND FLAG-2 = "Y" | Multiple criteria validation |
Write COBOL conditional logic to implement the following business rules for order processing:
1234567891011121314151617181920212223242526* Given these data items: 01 ORDER-DATA. 05 ORDER-AMOUNT PIC 9(6)V99. 05 CUSTOMER-TYPE PIC X(10). 05 SHIPPING-METHOD PIC X(10). 05 PAYMENT-METHOD PIC X(10). 01 PROCESSING-DATA. 05 DISCOUNT-PERCENTAGE PIC 9(2)V99. 05 SHIPPING-CHARGE PIC 9(4)V99. 05 PROCESSING-FEE PIC 9(3)V99. 05 RUSH-FEE PIC 9(3)V99 VALUE 25.00. 05 ORDER-STATUS PIC X(15). * Business Rules: * 1. Premium customers get 10% discount, Gold customers get 7.5% discount, * Regular customers get 5% discount for orders over $1000 or 0% otherwise * 2. Shipping is free for: * - Premium customers with orders over $500 * - Gold customers with orders over $1000 * - All other orders have a shipping charge of $25 for standard or $45 for expedited * 3. Credit card payments have a 2% processing fee, except for Premium customers * 4. Expedited shipping adds a $25 rush fee regardless of customer type * 5. Orders are marked "Processing" if all criteria are met, or "On Hold" otherwise * Your task: Write the conditional logic to implement these rules
Implement conditional logic to calculate employee bonuses based on performance ratings and tenure.
123456789101112131415161718192021222324252627282930313233343536373839404142* Given these data items: 01 EMPLOYEE-DATA. 05 EMPLOYEE-ID PIC 9(5). 05 EMPLOYEE-NAME PIC X(30). 05 DEPARTMENT PIC X(20). 05 SALARY PIC 9(6)V99. 05 YEARS-OF-SERVICE PIC 9(2). 05 PERFORMANCE-RATING PIC 9. *> 1=Poor, 2=Average, 3=Good, 4=Excellent, 5=Outstanding 01 BONUS-DATA. 05 BASE-PERCENT PIC 9(2)V99. 05 TENURE-ADDITION PIC 9(2)V99. 05 PERFORMANCE-MULTIPLIER PIC 9V99. 05 BONUS-AMOUNT PIC 9(6)V99. 05 ELIGIBLE-FLAG PIC X VALUE 'N'. * Bonus Calculation Rules: * 1. Base bonus percentage: * - Department "SALES": 5% of salary * - Department "IT" or "ENGINEERING": 4% of salary * - Department "FINANCE" or "ACCOUNTING": 3% of salary * - Department "ADMIN" or "HR": 2% of salary * - All other departments: 1% of salary * * 2. Years of service addition: * - 0-2 years: No addition * - 3-5 years: Add 1% to base percentage * - 6-10 years: Add 2% to base percentage * - 11+ years: Add 3% to base percentage * * 3. Performance multiplier: * - Rating 1 (Poor): No bonus (not eligible) * - Rating 2 (Average): Base multiplier 0.8 * - Rating 3 (Good): Base multiplier 1.0 * - Rating 4 (Excellent): Base multiplier 1.2 * - Rating 5 (Outstanding): Base multiplier 1.5 * * 4. Bonus calculation: * - Calculate: BONUS-AMOUNT = SALARY * (BASE-PERCENT + TENURE-ADDITION) * PERFORMANCE-MULTIPLIER * - Set ELIGIBLE-FLAG based on eligibility * * Your task: Write the conditional logic to implement this bonus calculation system
Write COBOL conditional logic to validate a customer record based on various criteria.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354* Given these data items: 01 CUSTOMER-RECORD. 05 CUSTOMER-ID PIC X(8). 05 CUSTOMER-NAME PIC X(30). 05 CUSTOMER-ADDRESS. 10 STREET PIC X(30). 10 CITY PIC X(20). 10 STATE PIC XX. 10 ZIP-CODE PIC X(10). 05 PHONE-NUMBER PIC X(15). 05 EMAIL PIC X(50). 05 CREDIT-LIMIT PIC 9(6)V99. 05 ACCOUNT-OPENED-DATE PIC 9(8). *> YYYYMMDD format 01 VALIDATION-RESULTS. 05 ERROR-COUNT PIC 9(3) VALUE ZERO. 05 ERROR-MESSAGES PIC X(80) OCCURS 10 TIMES. 05 RECORD-VALID PIC X VALUE 'Y'. * Validation Requirements: * 1. CUSTOMER-ID must: * - Not be spaces * - Start with letter "C" followed by 7 numeric digits * * 2. CUSTOMER-NAME must: * - Not be spaces * - Contain at least 3 characters * * 3. STREET, CITY must not be spaces * * 4. STATE must be a valid US state code (assume valid codes are in STATE-TABLE) * * 5. ZIP-CODE must contain only numeric digits or be in 99999-9999 format * * 6. PHONE-NUMBER must: * - Contain only digits, spaces, dashes, or parentheses * - Contain at least 10 digits * * 7. EMAIL (if not spaces) must: * - Contain "@" character * - Have at least one character before the "@" * - Have at least one "." after the "@" * * 8. CREDIT-LIMIT must be numeric and not negative * * 9. ACCOUNT-OPENED-DATE must: * - Be numeric * - Represent a valid date (YYYYMMDD format with valid month/day) * - Not be in the future * * Your task: Write the conditional logic to validate the customer record * Add appropriate error messages to ERROR-MESSAGES as needed * Increment ERROR-COUNT for each error found * Set RECORD-VALID to 'N' if any validation fails
Using named conditions for more readable code
Principles and practices for more maintainable code
Techniques for troubleshooting conditional logic issues
Understanding AND, OR, and NOT operators
Alternative approach for complex condition handling
1. What type of condition would you use to check if a field contains only numeric digits?
2. What is the proper way to test if a numeric value is negative in COBOL?
3. Which operator has the highest precedence in a complex condition?
4. What happens when the condition in an IF statement is false and there is no ELSE clause?
5. Which of the following is a valid way to check if a field equals either "A", "B", or "C"?