Chapter 11 Exercises: Sequential File Processing

These exercises are organized into five tiers of increasing difficulty, following Bloom's Taxonomy. Complete each tier before moving to the next. Selected solutions are provided in code/exercise-solutions.cob.


Tier 1: Remembering (Exercises 1-8)

Recall facts, terms, and basic concepts about sequential file processing.

Exercise 1: SELECT Statement Components

Write the complete ENVIRONMENT DIVISION entries (INPUT-OUTPUT SECTION and FILE-CONTROL) for a program that reads an employee file (EMPFILE, sequential, FB LRECL=80) and writes a report file (RPTFILE, sequential). Include FILE STATUS clauses for both files.

Exercise 2: FD Entry

Write the FD entry and 01-level record description for a customer file with the following fields: - Customer ID (8 characters) - Customer Name (30 characters) - Address (30 characters) - City (20 characters) - State (2 characters) - ZIP Code (5 characters) - Balance (7 digits with 2 decimal places) - Account Type (1 character) - Last Activity Date (8 digits, YYYYMMDD)

Ensure the total record length is 120 bytes (pad with FILLER as needed).

Exercise 3: File Status Conditions

Define a WORKING-STORAGE file status variable with 88-level conditions for the following status codes: success (00), end-of-file (10), file not found (35), permanent error (30), boundary violation (34), and file locked (38).

Exercise 4: Basic READ Loop

Write the PROCEDURE DIVISION paragraphs for a program that reads a sequential file and displays each record. Use the priming read pattern. Include file status checking after the OPEN and after each READ.

Exercise 5: Record Counting by Category

Write a complete program that reads an employee file (80-byte records with department in positions 42-45) and counts the number of records for each of four departments: ACCT, SALE, TECH, and OTHER. Display the counts at the end. (Solution provided)

Exercise 6: WRITE Statement Practice

Write the PROCEDURE DIVISION code to create a new sequential file containing 5 records. Build each record in WORKING-STORAGE and use WRITE...FROM to write it. Check file status after each WRITE.

Exercise 7: OPEN Modes

For each of the following scenarios, state which OPEN mode (INPUT, OUTPUT, EXTEND, I-O) should be used: 1. Reading a customer master file 2. Creating a new report file 3. Appending entries to a log file 4. Reading a file and updating records in place

Exercise 8: JCL DD Statements

Write the JCL DD statements for: 1. An input file: PROD.CUSTOMER.MASTER, shared access, FB LRECL=120 2. A new output file: PROD.CUSTOMER.REPORT, FB LRECL=133, allocated 2 primary cylinders and 1 secondary, released unused space 3. A SYSOUT report with FBA LRECL=133


Tier 2: Understanding (Exercises 9-14)

Explain ideas, interpret concepts, and compare approaches.

Exercise 9: Priming Read Explanation

Explain why the priming read pattern is necessary. What would happen if you wrote the loop as follows? Identify the specific problem.

           PERFORM UNTIL END-OF-FILE
               READ EMPLOYEE-FILE
                   AT END SET END-OF-FILE TO TRUE
               END-READ
               PERFORM PROCESS-RECORD
           END-PERFORM

Exercise 10: File Filter

Write a program that reads an employee file and copies only those records where the salary exceeds $50,000.00 to an output file. Display counts of records read, written, and skipped. (Solution provided)

Exercise 11: Fixed vs. Variable Length

Explain the differences between fixed-length and variable-length records. For each of the following scenarios, state whether you would use fixed or variable-length records and explain why: 1. Employee master file with standard fields 2. Order file where each order has 1 to 100 line items 3. Monthly bank statement with varying transaction counts 4. Fixed-format payment file required by government specification

Exercise 12: BLOCK CONTAINS Analysis

Explain what BLOCK CONTAINS 0 RECORDS means and why it is preferred over specifying an explicit block count. What role does the JCL DCB BLKSIZE parameter play when BLOCK CONTAINS 0 is specified?

Exercise 13: File Status Scenarios

For each of the following scenarios, state the expected file status code and what the program should do in response: 1. Successfully reading a record 2. Reading past the last record in a file 3. Opening a file for INPUT when the data set does not exist 4. Writing to a file when the allocated disk space is full 5. Opening a file that is already open 6. The COBOL FD says LRECL=80 but the JCL says LRECL=100

Exercise 14: WRITE vs. READ Syntax

Explain why READ operates on the file name (READ EMPLOYEE-FILE) while WRITE operates on the record name (WRITE EMP-RECORD). What is the practical implication when a file has multiple 01-level record descriptions?


Tier 3: Applying (Exercises 15-22)

Use learned concepts to solve new problems.

Exercise 15: Two-File Merge

Write a complete program that merges two sorted sequential files (FILE-A and FILE-B, both sorted by an 8-character key in positions 1-8) into a single sorted output file (MERGED-FILE). Both input files have 80-byte records. Use the balanced line algorithm with HIGH-VALUES sentinels. Display record counts for all three files. (Solution provided)

Exercise 16: Sequential Copy with Statistics

Write a program that copies a sequential file and produces the following statistics: - Total record count - Count of records with blank fields (any field that is entirely spaces) - Minimum, maximum, and average salary (assuming salary is in positions 42-50, PIC 9(7)V99) - Count of records per department (department in positions 37-40)

Exercise 17: Simple Report

Write a program that reads a sorted employee file (sorted by department) and produces a simple report with: - A title line with the report name and date - Column headings - One detail line per employee showing ID, name, department, and salary - A record count at the end Use the ADVANCING clause for spacing. No control breaks are needed for this exercise.

Exercise 18: JCL for Multi-Step Job

Write complete JCL for a job that: 1. Sorts an input file by account number (positions 1-8, character, ascending) 2. Runs a COBOL program (UPDTMAST) that reads the sorted file and a master file, and produces a new master file and error report 3. Uses IDCAMS to verify the new master file was created

Include all DD statements with appropriate DISP, SPACE, and DCB parameters. Use COND parameters to prevent subsequent steps from running if a prior step fails.

Exercise 19: Variable-Length Record Processing

Write a program that reads a variable-length order file (RECORD CONTAINS 30 TO 500 CHARACTERS) where each order has a fixed header (30 bytes including a 2-digit line count) followed by 0 to 20 line items (23 bytes each, using OCCURS DEPENDING ON). The program should: - Display each order's header information - Display each line item within the order - Calculate and display the total quantity across all orders - Write orders with more than 10 line items to a separate "large orders" output file

Exercise 20: Transaction Validation

Write a program that reads a transaction file and validates each record. Valid records are written to an output file; invalid records are written to an error file with the reason for rejection. Validate: - Account number is not blank - Transaction type is 'A', 'C', or 'D' - Amount is greater than zero - Date is not zero Display statistics showing total read, valid count, and error count. (Solution provided)

Exercise 21: File Comparison

Write a program that reads two files (FILE-A and FILE-B), both sorted by an 8-character key, and produces three output files: - MATCH-FILE: Records where the key appears in both files (write file A's record) - A-ONLY-FILE: Records that appear only in FILE-A - B-ONLY-FILE: Records that appear only in FILE-B

Display counts for each category.

Exercise 22: EXTEND Mode Log Program

Write a program that appends timestamped entries to a log file using OPEN EXTEND. The program should: - Accept the current date and time using ACCEPT FROM DATE and ACCEPT FROM TIME - Build a log record with: timestamp, program name, a message passed via WORKING-STORAGE - Append 3 log entries: START, PROCESSING, and COMPLETE - Display the entries as they are written

Write the companion JCL, noting the correct DISP for an EXTEND operation (use MOD).


Tier 4: Analyzing (Exercises 23-30)

Break down problems, identify patterns, and diagnose issues.

Exercise 23: Debug the Program

The following program has five bugs. Find and fix all of them.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. BUGGY.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT INPUT-FILE
               ASSIGN TO INFILE
               ORGANIZATION IS SEQUENTIAL.
       DATA DIVISION.
       FILE SECTION.
       FD  INPUT-FILE
           RECORD CONTAINS 80 CHARACTERS.
       01  IN-REC.
           05  IN-KEY    PIC X(08).
           05  IN-NAME   PIC X(30).
           05  IN-AMOUNT PIC 9(05)V99.
           05  FILLER    PIC X(25).
       WORKING-STORAGE SECTION.
       01  WS-EOF PIC X VALUE 'N'.
           88 EOF VALUE 'Y'.
       01  WS-COUNT PIC 9(05) VALUE ZERO.
       PROCEDURE DIVISION.
           OPEN INPUT INPUT-FILE
           PERFORM UNTIL EOF
               READ INPUT-FILE
                   AT END SET EOF TO TRUE
               END-READ
               ADD 1 TO WS-COUNT
               DISPLAY IN-KEY ' ' IN-NAME ' ' IN-AMOUNT
           END-PERFORM
           DISPLAY 'COUNT: ' WS-COUNT
           STOP RUN.

Exercise 24: Sequential Update Error Analysis

Given the following old master file and transaction file (both sorted by key), trace through the balanced line algorithm and determine the contents of the new master file and which transactions generate errors:

Old Master:

100 Alice   50000
200 Bob     60000
300 Carol   45000
500 Eve     70000

Transactions:

100 C 55000  (Change salary to 55000)
150 A 40000  (Add new record)
200 D        (Delete)
200 C 65000  (Change salary - duplicate key!)
300 A 50000  (Add - record exists!)
400 A 48000  (Add new record)
600 D        (Delete - no master!)

Exercise 25: Control Break Report

Write a complete report program that reads a sales file sorted by region (4-char region code in positions 1-4) and produces a report with: - Page headers with title and page number - Region group headers - Detail lines for each sale - Region subtotals (count and amount) - Grand totals - Page breaks when the page is full (55 lines per page) (Solution provided)

Exercise 26: Performance Analysis

A batch job reads a 10-million-record sequential file (LRECL=200, RECFM=FB). Analyze the impact of the following BLKSIZE values on the number of physical I/O operations: 1. BLKSIZE=200 (unblocked) 2. BLKSIZE=6000 (30 records per block) 3. BLKSIZE=27800 (139 records per block, near half-track) 4. BLKSIZE=0 (system-determined)

Estimate the number of physical I/O operations for each case (assume 3390 device with 56,664 bytes per track).

Exercise 27: Error Recovery Design

Design a COBOL program structure (pseudocode or paragraph-level outline) for a program that must handle the following error recovery scenarios: 1. Input file not found: Try an alternate file name, then ABEND with return code 12 2. Output disk full: Close the output file, display a warning, open a new output file on an alternate volume, and continue 3. Read error on record N: Write an error record, skip the bad record, and continue processing 4. Multiple consecutive read errors (3 in a row): ABEND with return code 16

Exercise 28: JCL Analysis

Explain what each line of the following JCL does. Identify any potential problems.

//MYJOB    JOB (ACCT),'MYNAME',CLASS=A,MSGCLASS=X,
//         MSGLEVEL=(1,1),NOTIFY=&SYSUID
//STEP1    EXEC PGM=MYPROG
//STEPLIB  DD DSN=MY.LOADLIB,DISP=SHR
//INFILE   DD DSN=PROD.MASTER.FILE,DISP=OLD
//OUTFILE  DD DSN=PROD.NEW.MASTER,
//         DISP=(NEW,CATLG,CATLG),
//         SPACE=(TRK,(10,5)),
//         DCB=(RECFM=FB,LRECL=80,BLKSIZE=800)
//SYSOUT   DD SYSOUT=*

Exercise 29: Multi-Level Control Break

Write a program that produces a report with two levels of control break. Given a file sorted by region within district (district in positions 1-4, region in positions 5-8), produce: - Detail lines for each record - Region subtotals when the region changes - District subtotals when the district changes (which also triggers a region subtotal) - Grand totals at the end

Exercise 30: File Format Conversion

Write a program that converts a variable-length file (VB, LRECL=504, minimum 20 bytes) to a fixed-length file (FB, LRECL=500) by padding short records with spaces and truncating records longer than 500 bytes. Write truncated records to an exception file. Report counts of: records converted, records padded, records truncated.


Tier 5: Creating (Exercises 31-40)

Design and build complete solutions for complex scenarios.

Exercise 31: Complete Payroll Processing System

Design and write a sequential file update program for a payroll system. The program must: 1. Read an employee master file (LRECL=120) containing: employee ID (6), name (30), department (4), base salary (7V2), tax bracket (2), benefit code (2), YTD gross (9V2), YTD tax (9V2), YTD net (9V2), and filler 2. Read a payroll transaction file (LRECL=80) with: employee ID (6), hours worked (3V1), overtime hours (2V1), bonus (5V2), deductions (5V2), and payroll period end date (8) 3. Calculate gross pay (base salary / 26 pay periods + overtime * 1.5 rate + bonus) 4. Calculate taxes based on tax bracket (15%, 25%, 28%, 33%) 5. Calculate net pay 6. Update YTD accumulators 7. Write new master file 8. Produce a formatted paycheck register report with department subtotals and grand totals

Write the companion JCL for the complete job.

Exercise 32: File Reconciliation System

Write a program that reconciles two independently produced files of the same data (e.g., a bank's internal transaction file and a payment processor's settlement file). The program must: 1. Read both files (sorted by transaction ID) 2. Match records by ID 3. For matched records, compare amount fields and flag discrepancies 4. Identify records in file A but not file B (and vice versa) 5. Produce a reconciliation report showing matches, mismatches, and unmatched records 6. Produce a summary with counts and total amounts for each category

Exercise 33: Data Migration Program

Write a program that migrates data from an old record format to a new format: - Old format (LRECL=80): account(8), name(25), balance(7V2), date(6 YYMMDD), status(1), filler(31) - New format (LRECL=120): account(10, padded with leading zeros), name(30, uppercased), balance(9V2), date(8 YYYYMMDD, century-adjusted), status(2, expanded), audit-trail(20), create-date(8), filler(25)

Handle century adjustment: years 00-30 become 2000-2030; years 31-99 become 1931-1999. Expand status: 'A' becomes 'AC', 'C' becomes 'CL', 'S' becomes 'SU'. Generate an audit trail ID based on the migration date and a sequence number.

Exercise 34: Multi-File Report Generator

Write a program that reads three input files (customers, orders, and products) and produces a customer order summary report. Each customer may have multiple orders, and each order references products by ID. The report should show: - Customer information - Each order placed by the customer - Product details for each order line - Customer total - Grand total

All three files are sorted by customer ID. Design the file layouts, write the program, and write the JCL.

Exercise 35: Audit Trail System

Design and implement a complete audit trail system that: 1. Reads an original master file and a new master file (output of an update program) 2. Compares every record to identify adds, changes, and deletes 3. For changes, identifies which specific fields changed 4. Writes an audit trail file with: timestamp, change type, key, old values, new values 5. Produces a change summary report

Exercise 36: Government Payment File Generator

Write the program described in Case Study 2: a government benefits payment file generator. The program reads a beneficiary master file and generates a fixed-format payment file according to a specification: - Header record (record type 'H', file date, agency code, sequence number) - Detail records (record type 'D', beneficiary ID, payment amount, payment date, payment method code) - Trailer record (record type 'T', record count, total amount, hash total of beneficiary IDs)

Include validation, reconciliation, and error reporting. Write the companion JCL.

Exercise 37: Batch Job Stream Design

Design a complete batch job stream (multiple JCL steps and COBOL programs) for a nightly processing cycle at an insurance company: 1. Extract new claims from the daily claim file 2. Validate claims against policy master file 3. Update the claim history file 4. Calculate reserves for valid claims 5. Generate a daily claims register report 6. Generate exception reports for invalid claims

Write the JCL for the entire job stream and the COBOL program for step 3 (the claim history update).

Exercise 38: File Split and Distribution

Write a program that reads a large sequential file and splits it into multiple output files based on a routing code in each record. Support up to 10 output files. The program must: - Open all output files dynamically based on routing codes encountered - Route each record to the correct output file - Handle records with invalid routing codes (write to an error file) - Produce a distribution summary showing record counts per routing code

Exercise 39: Sequential File Sort Verification

Write a utility program that verifies whether a sequential file is correctly sorted. The program should: - Accept the sort key position, length, and data type as parameters - Read the file and compare each key with the previous key - Detect and report all out-of-sequence records with their positions - Optionally check for duplicate keys - Report: total records, in-sequence count, out-of-sequence count, duplicate count

Exercise 40: Complete Banking Batch Cycle

Implement the full nightly batch cycle described in Case Study 1, including: 1. Transaction sort program (or SORT JCL step) 2. Master file update program with all transaction types 3. Interest calculation program (daily interest on savings accounts) 4. Statement generation program (monthly statements for accounts with activity) 5. Regulatory reporting program (accounts exceeding $10,000 in daily transactions) 6. Complete JCL job stream connecting all steps

This is a capstone exercise. Aim for production-quality code with full error handling, meaningful return codes, and comprehensive statistics reporting.