MainframeMaster

COBOL Tutorial

Conditional Execution

Progress0 of 0 lessons

Introduction to Conditional Execution

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.

Types of Conditions in COBOL

  • Relational Conditions: Compare values using operators (=, >, <, etc.)
  • Class Conditions: Test if data is NUMERIC, ALPHABETIC, etc.
  • Sign Conditions: Test if a value is POSITIVE, NEGATIVE, or ZERO
  • Condition-Name Conditions: Use 88-level items to test for specific values
  • Complex Conditions: Combine conditions using AND, OR, and NOT
  • Abbreviated Conditions: Shorthand notation for repeated conditions

Conditional Structures in COBOL

StructurePurposeKey Features
Simple IFBasic condition testingExecute statements only if condition is true
IF-ELSEBinary decisionDifferent actions for true and false conditions
Nested IFMulti-level decisionsConditions within conditions
EVALUATEMulti-way branchingCase/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.

IF Statement Syntax

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.

IF Statement Formats

Format 1: Simple IF

cobol
1
2
3
4
5
IF condition statement-1 statement-2 ... END-IF

Format 2: IF-ELSE

cobol
1
2
3
4
5
6
7
8
9
IF condition statement-1 statement-2 ... ELSE statement-3 statement-4 ... END-IF

Format 3: Nested IF

cobol
1
2
3
4
5
6
7
8
9
10
11
IF condition-1 statement-1 IF condition-2 statement-2 ELSE statement-3 END-IF statement-4 ELSE statement-5 END-IF

IF Statement Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
* 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.

Key Points About IF Statements

  • The IF statement tests a condition and executes the following statements only if the condition is true
  • The ELSE clause is optional and executes only if the condition is false
  • The END-IF scope terminator explicitly marks the end of the IF statement
  • In modern COBOL, END-IF is required for nested IF statements for clarity
  • Multiple statements can be executed in both the IF and ELSE blocks
  • Nested IF statements allow for complex decision trees
  • COBOL does not have an "ELSE IF" construct like other languages; use nested IFs instead
  • For multiple conditions, consider using the EVALUATE statement instead of deeply nested IFs
  • Proper indentation improves readability, especially for nested structures

Common IF Statement Pitfalls

IssueImpactSolution
Missing END-IFAmbiguous scope, incorrect execution flowAlways use END-IF terminators
Deeply nested IFsCode becomes difficult to follow and maintainUse EVALUATE or extract to separate paragraphs
Missing ELSE clauseMay not handle all possible casesInclude ELSE or document why it's intentionally omitted
Complex conditionsError-prone logic, hard to debugBreak down into simpler conditions, use 88-level items

Relational Conditions

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.

Relational Operators

OperatorMeaningExample
IS EQUAL TO, =EqualIF A = B
IS GREATER THAN, >Greater thanIF A > B
IS LESS THAN, <Less thanIF A < B
IS GREATER THAN OR EQUAL TO, >=Greater than or equalIF A >= B
IS LESS THAN OR EQUAL TO, <=Less than or equalIF A <= B
IS NOT EQUAL TO, <>Not equalIF A <> B

Note: The word "IS" is optional in these operators and is often omitted.

Relational Condition Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
* 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.

Key Points About Relational Conditions

  • Data Types: When comparing items, they should be of compatible data types:
    • Numeric items can be compared with other numeric items
    • Alphanumeric items can be compared with other alphanumeric items
    • Group items are treated as alphanumeric
  • Comparison Rules:
    • Numeric comparisons are algebraic (based on value)
    • Alphanumeric comparisons are based on the collating sequence (usually EBCDIC or ASCII)
    • For alphanumeric items, the comparison is left-to-right, character by character
    • If items have different lengths, the shorter item is conceptually padded with spaces
  • Unsigned Numbers: When comparing unsigned numeric items, the absence of a sign is treated as positive
  • Group Items: When comparing group items, the comparison is based on the binary value of each character, not the actual content meaning
  • National Characters: Special considerations apply when comparing DBCS or Unicode data

Comparing Different Types of Data

Comparison TypeDescriptionExample
Numeric to numericBased on algebraic valueIF SALARY > THRESHOLD
Numeric to numeric literalBased on algebraic valueIF QUANTITY < 10
Alphanumeric to alphanumericCharacter-by-characterIF NAME = OTHER-NAME
Alphanumeric to alphanumeric literalCharacter-by-characterIF CODE = "ABC"
Group to groupTreated as alphanumericIF RECORD-1 = RECORD-2

Common Pitfalls with Relational Conditions

  • Comparing Incompatible Data Types: Avoid comparing numerics with alphanumerics directly; convert as needed
  • Ignoring Field Lengths: Be careful when comparing fields of different lengths, especially with trailing spaces
  • Numeric Precision Issues: Be aware of COMP fields with different precisions
  • Character Set Dependencies: Alphanumeric comparisons depend on the system's collating sequence
  • Missing Equality Test: Testing only for greater/less than without considering equality
  • Special Values: Watch for special values like HIGH-VALUES, LOW-VALUES, or SPACES in comparisons

Class Conditions

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 Condition Types

Class TestDescriptionExample
NUMERICContains only digits (0-9) and possibly a signIF AMOUNT IS NUMERIC
ALPHABETICContains only letters (A-Z, a-z) and spacesIF NAME IS ALPHABETIC
ALPHABETIC-LOWERContains only lowercase letters (a-z) and spacesIF FIELD IS ALPHABETIC-LOWER
ALPHABETIC-UPPERContains only uppercase letters (A-Z) and spacesIF FIELD IS ALPHABETIC-UPPER
ALPHANUMERICContains any character in the computer's character setIF FIELD IS ALPHANUMERIC
DBCS, KANJI (in some dialects)Contains only valid double-byte charactersIF 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).

Class Condition Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
* 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.

Key Points About Class Conditions

  • NUMERIC Test:
    • Item must be defined as USAGE DISPLAY or NATIONAL
    • Contains only digits 0-9 (and possibly a sign)
    • If signed, the operational sign must be valid
    • Cannot contain decimal point character (period)
    • Empty or all-spaces item is NOT considered numeric
  • ALPHABETIC Test:
    • Item must be defined as USAGE DISPLAY
    • Contains only letters A-Z, a-z and spaces
    • Cannot contain digits, special characters, or punctuation
    • An all-spaces item IS considered alphabetic
  • Group Items:
    • Class conditions can be applied to group items
    • The condition applies to the entire group, not individual fields
    • For NUMERIC test on a group, all character positions must be numeric
  • Usage Considerations:
    • NUMERIC test applies only to DISPLAY or NATIONAL usage items
    • COMP, COMP-3 fields cannot be tested with class conditions directly
    • For packed or binary fields, use a temporary DISPLAY field for testing

Common Uses for Class Conditions

ScenarioClass TestExample
User input validationNUMERIC, ALPHABETICEnsuring phone numbers are numeric, names are alphabetic
Data conversion preparationNUMERICChecking if a field can be converted to a numeric value
File record validationVariousValidating data in imported files before processing
Code format validationALPHABETIC-UPPEREnsuring standardized codes are in correct format

Sign Conditions

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 Condition Types

Sign TestDescriptionExample
POSITIVEValue is greater than zeroIF AMOUNT IS POSITIVE
NEGATIVEValue is less than zeroIF AMOUNT IS NEGATIVE
ZEROValue is exactly zeroIF AMOUNT IS ZERO

Note: The IS keyword is optional. NOT can be used to negate the test (e.g., IF AMOUNT IS NOT POSITIVE).

Sign Condition Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
* 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.

Key Points About Sign Conditions

  • Applicable Data Items:
    • Sign conditions can only be used with numeric data items
    • The item can be of any USAGE (DISPLAY, COMP, etc.)
    • Group items cannot be used with sign conditions
  • Unsigned Data:
    • An unsigned numeric item is considered POSITIVE if its value is greater than zero
    • An unsigned numeric item can be ZERO
    • An unsigned numeric item cannot be NEGATIVE
  • Alternative Expressions:
    • IF AMOUNT IS POSITIVE is equivalent to IF AMOUNT > 0
    • IF AMOUNT IS NEGATIVE is equivalent to IF AMOUNT < 0
    • IF AMOUNT IS ZERO is equivalent to IF AMOUNT = 0
  • Common Usage Patterns:
    • Used for financial calculations and account status checking
    • Used for inventory level monitoring
    • Helpful for business rule implementations involving quantities

Sign Conditions vs. Relational Conditions

FeatureSign ConditionsRelational Conditions
SyntaxIF amount IS POSITIVEIF amount > 0
ReadabilityMore explicit for sign testsMore versatile for general comparisons
FunctionalityLimited to sign testingCan compare against any value
Usage in codeBetter communicates intent for sign testingBetter 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 with AND/OR

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.

Logical Operators

OperatorDescriptionExample
ANDBoth conditions must be trueIF A > 0 AND B > 0
ORAt least one condition must be trueIF A = 1 OR A = 2
NOTNegates a conditionIF NOT (A = B)

Complex Condition Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
* 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.

Order of Evaluation

  1. Expressions within parentheses are evaluated first
  2. NOT operators are applied next
  3. AND operators are applied next
  4. OR operators are applied last

To ensure clarity and avoid mistakes, it's recommended to use parentheses to explicitly specify the order of evaluation, even when not strictly necessary.

Key Points About Complex Conditions

  • AND Logic:
    • All conditions connected by AND must be true for the entire condition to be true
    • If any condition is false, the entire condition is false
    • COBOL evaluates AND conditions from left to right, and may use short-circuit evaluation
  • OR Logic:
    • At least one condition connected by OR must be true for the entire condition to be true
    • If all conditions are false, the entire condition is false
    • COBOL evaluates OR conditions from left to right, and may use short-circuit evaluation
  • NOT Logic:
    • NOT reverses the truth value of the condition
    • NOT has higher precedence than AND and OR
    • Multiple NOTs cancel each other (NOT NOT A is equivalent to A)
  • Parentheses:
    • Use parentheses to group conditions and control evaluation order
    • Parentheses can be nested to any level
    • Conditions in parentheses are evaluated first, from innermost to outermost

Common Logical Patterns

Logical PatternCOBOL ExpressionExample Use Case
Range checkA >= B AND A <= CAge validation, date range check
Multiple valid valuesA = B OR A = C OR A = DStatus codes, transaction types
ExclusionNOT (A = B)Skipping certain records
Conditional qualification(A = B AND C > D) OR (A = E AND C > F)Tiered business rules
Boolean flag checkFLAG-1 = "Y" AND FLAG-2 = "Y"Multiple criteria validation

Common Pitfalls with Complex Conditions

  • Operator Precedence Mistakes: Misunderstanding order of evaluation (use parentheses)
  • Logic Errors: Using AND when OR is needed or vice versa
  • Redundant Conditions: Writing unnecessarily complicated expressions
  • Missing Parentheses: Failing to group conditions correctly
  • Double Negation: Using NOT with negative conditions (harder to understand)
  • Boundary Cases: Not handling edge cases properly in logical expressions

Exercises: Conditional Execution

Exercise 1: Order Processing Logic

Write COBOL conditional logic to implement the following business rules for order processing:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
* 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

Exercise 2: Employee Bonus Calculation

Implement conditional logic to calculate employee bonuses based on performance ratings and tenure.

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
* 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

Exercise 3: Input Validation

Write COBOL conditional logic to validate a customer record based on various criteria.

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
* 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

Frequently Asked Questions

Test Your Knowledge

1. What type of condition would you use to check if a field contains only numeric digits?

  • Relational condition
  • Class condition
  • Sign condition
  • Complex condition

2. What is the proper way to test if a numeric value is negative in COBOL?

  • IF NUMBER < 0
  • IF NUMBER IS NEGATIVE
  • Both of the above are correct
  • IF SIGN OF NUMBER IS MINUS

3. Which operator has the highest precedence in a complex condition?

  • AND
  • OR
  • NOT
  • All have equal precedence

4. What happens when the condition in an IF statement is false and there is no ELSE clause?

  • The program terminates
  • The program skips to the next paragraph
  • Execution continues with the statement following the IF or END-IF
  • The program raises an exception

5. Which of the following is a valid way to check if a field equals either "A", "B", or "C"?

  • IF FIELD = ANY OF "A", "B", "C"
  • IF FIELD = "A" OR "B" OR "C"
  • IF FIELD = "A" OR FIELD = "B" OR FIELD = "C"
  • IF FIELD IN ("A", "B", "C")