Chapter 13 Exercises: Relative File Processing and Advanced File Techniques
Tier 1: Recall and Recognition (Exercises 1-8)
Exercise 1: SELECT Clause for Relative Files
Write the complete SELECT clause for a relative file with the following characteristics: - File name: ACCOUNT-SLOTS - External name: ACCTSLOT - Access mode: Random - Relative key field: WS-ACCT-SLOT-NUM - File status field: WS-SLOT-STATUS
Answer:
SELECT ACCOUNT-SLOTS
ASSIGN TO ACCTSLOT
ORGANIZATION IS RELATIVE
ACCESS MODE IS RANDOM
RELATIVE KEY IS WS-ACCT-SLOT-NUM
FILE STATUS IS WS-SLOT-STATUS.
Exercise 2: Relative File Terminology
Fill in the blanks:
a) In a relative file, each record is identified by its _ _ ____, which is its ordinal position within the file.
b) The RELATIVE KEY field must be defined in _ _, not in the file's FD record description.
c) The minimum valid relative record number is ____.
d) The formula to calculate the byte offset for a record is: byte-offset = (_ - 1) * _.
e) On z/OS, a relative file is typically stored as a VSAM ____ (abbreviation).
Answers: a) relative record number b) WORKING-STORAGE SECTION c) 1 (there is no record 0) d) record-number, record-length e) RRDS (Relative Record Data Set)
Exercise 3: Access Mode Comparison
For each of the following banking scenarios, identify the most appropriate ACCESS MODE for a relative file (SEQUENTIAL, RANDOM, or DYNAMIC):
a) Loading all 10,000 branch slot records from a sorted flat file into a new relative file b) Looking up a specific teller window assignment by window number during peak hours c) Starting at slot 500 and reading forward to find the next 20 occupied slots, then jumping to slot 8000 d) Producing a nightly report listing every occupied slot in order e) An ATM locator that reads a specific branch record, then browses nearby branches sequentially
Answers: a) SEQUENTIAL -- loading records in order from 1 to N b) RANDOM -- direct lookup by known slot number c) DYNAMIC -- combination of sequential browsing and random jumps d) SEQUENTIAL -- reading all records in order e) DYNAMIC -- random lookup followed by sequential browsing
Exercise 4: File Status Codes for Relative Files
Match each file status code to the condition it indicates during relative file processing:
| Code | Meaning |
|---|---|
| 00 | _ |
| 10 | _ |
| 22 | _ |
| 23 | _ |
| 24 | _ |
| 30 | _ |
Choose from: Successful completion, End of file (no more records), Duplicate key (slot already occupied), Record not found (empty slot), Boundary violation (relative key too large or zero), Permanent I/O error.
Answers: 00 = Successful completion, 10 = End of file (no more records), 22 = Duplicate key (slot already occupied), 23 = Record not found (empty slot), 24 = Boundary violation (relative key too large or zero), 30 = Permanent I/O error.
Exercise 5: RELATIVE KEY Rules
Answer True or False for each statement about the RELATIVE KEY:
a) The RELATIVE KEY can be defined within the FD record description. b) The RELATIVE KEY must be an unsigned integer field. c) After a sequential READ, the RELATIVE KEY is updated with the number of the record just read. d) Setting the RELATIVE KEY to zero and performing a READ is valid. e) The RELATIVE KEY clause is optional when ACCESS MODE IS SEQUENTIAL.
Answers: a) False -- must be in WORKING-STORAGE, not in the FD. b) True -- no sign, no decimal places. c) True -- the system updates it automatically. d) False -- the minimum valid value is 1. e) True -- for SEQUENTIAL access only, the RELATIVE KEY clause is optional (but recommended for tracking which record was just read).
Exercise 6: OPEN Modes for Relative Files
For each operation on a relative file, identify the minimum OPEN mode required (INPUT, OUTPUT, I-O, or EXTEND):
a) READ a specific record by slot number b) WRITE a new record to an existing file using random access c) REWRITE an existing record d) DELETE a record by slot number e) Load records sequentially into a brand-new file f) Append records to the end of an existing relative file
Answers: a) INPUT (or I-O) b) I-O (must be I-O for random WRITE to existing file; OUTPUT creates a new file) c) I-O d) I-O e) OUTPUT f) EXTEND (sequential access only)
Exercise 7: LINAGE Clause Identification
Write an FD entry for a bank statement print file that uses the LINAGE clause with: - 60 printable lines per page - 3-line top margin (footing area at line 57) - A bottom margin handled by the LINAGE-COUNTER check
Answer:
FD STMT-PRINT-FILE
LINAGE IS 60 LINES
WITH FOOTING AT 57
LINES AT TOP 3
LINES AT BOTTOM 3.
01 STMT-PRINT-REC PIC X(132).
Exercise 8: Relative vs. Indexed vs. Sequential
Complete the comparison table:
| Feature | Sequential | Indexed (KSDS) | Relative (RRDS) |
|---|---|---|---|
| Key type | None | ___ | ___ |
| Access by key | ___ | Yes | ___ |
| Variable-length records | Yes | Yes | ___ |
| Empty slot support | ___ | ___ | Yes |
| VSAM type on z/OS | ESDS | ___ | ___ |
Answers: | Feature | Sequential | Indexed (KSDS) | Relative (RRDS) | |---------|-----------|----------------|------------------| | Key type | None | Alphanumeric field | Record number (integer) | | Access by key | No | Yes | Yes (by position) | | Variable-length records | Yes | Yes | No (fixed-length only) | | Empty slot support | No | No | Yes | | VSAM type on z/OS | ESDS | KSDS | RRDS |
Tier 2: Comprehension and Application (Exercises 9-16)
Exercise 9: Predict the Output
Study the following code carefully and predict the exact output:
WORKING-STORAGE SECTION.
01 WS-REL-KEY PIC 9(4).
01 WS-STATUS PIC XX.
01 WS-NAME PIC X(20).
...
PROCEDURE DIVISION.
OPEN I-O BRANCH-FILE
MOVE 5 TO WS-REL-KEY
READ BRANCH-FILE INTO WS-NAME
INVALID KEY
DISPLAY "SLOT " WS-REL-KEY " EMPTY"
NOT INVALID KEY
DISPLAY "SLOT " WS-REL-KEY ": " WS-NAME
END-READ
MOVE 0 TO WS-REL-KEY
READ BRANCH-FILE INTO WS-NAME
INVALID KEY
DISPLAY "INVALID: STATUS=" WS-STATUS
NOT INVALID KEY
DISPLAY "SLOT " WS-REL-KEY ": " WS-NAME
END-READ
CLOSE BRANCH-FILE
STOP RUN.
Assume slot 5 contains "DOWNTOWN BRANCH" and the file has 100 slots.
Answer: The output would be:
SLOT 0005: DOWNTOWN BRANCH
INVALID: STATUS=23
The first READ succeeds because slot 5 is occupied. The second READ fails because relative record number 0 is invalid (the minimum is 1). Some implementations may return status 23 (record not found) or 24 (boundary violation) for a zero key. The INVALID KEY clause catches both cases.
Exercise 10: Writing a Relative File Loader
Write a complete COBOL program that creates a relative file to store bank teller window assignments. The input is a sequential file with records containing: - Window Number: PIC 9(3) at position 1 (this becomes the relative key) - Teller ID: PIC X(6) at position 4 - Teller Name: PIC X(25) at position 10 - Branch Code: PIC X(4) at position 35 - Shift Code: PIC X(1) at position 39 ('M'=morning, 'A'=afternoon, 'E'=evening) - Filler: PIC X(41) at position 40 (total record = 80 bytes)
The program should skip records where Window Number is zero or non-numeric, count successful writes and duplicates, and display final statistics.
Answer:
IDENTIFICATION DIVISION.
PROGRAM-ID. RELLOAD.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPUT-FILE ASSIGN TO INFILE
FILE STATUS IS WS-IN-STATUS.
SELECT WINDOW-FILE ASSIGN TO WINFILE
ORGANIZATION IS RELATIVE
ACCESS MODE IS RANDOM
RELATIVE KEY IS WS-REL-KEY
FILE STATUS IS WS-WIN-STATUS.
DATA DIVISION.
FILE SECTION.
FD INPUT-FILE.
01 INPUT-REC.
05 IN-WINDOW-NUM PIC 9(3).
05 IN-TELLER-ID PIC X(6).
05 IN-TELLER-NAME PIC X(25).
05 IN-BRANCH-CODE PIC X(4).
05 IN-SHIFT-CODE PIC X(1).
05 FILLER PIC X(41).
FD WINDOW-FILE.
01 WINDOW-REC.
05 WF-TELLER-ID PIC X(6).
05 WF-TELLER-NAME PIC X(25).
05 WF-BRANCH-CODE PIC X(4).
05 WF-SHIFT-CODE PIC X(1).
05 FILLER PIC X(44).
WORKING-STORAGE SECTION.
01 WS-IN-STATUS PIC XX.
01 WS-WIN-STATUS PIC XX.
01 WS-REL-KEY PIC 9(4).
01 WS-READ-CTR PIC 9(6) VALUE 0.
01 WS-WRITE-CTR PIC 9(6) VALUE 0.
01 WS-DUP-CTR PIC 9(6) VALUE 0.
01 WS-SKIP-CTR PIC 9(6) VALUE 0.
01 WS-EOF-FLAG PIC X VALUE 'N'.
88 END-OF-INPUT VALUE 'Y'.
PROCEDURE DIVISION.
0000-MAIN.
OPEN INPUT INPUT-FILE
OPEN OUTPUT WINDOW-FILE
PERFORM 1000-READ-INPUT
PERFORM UNTIL END-OF-INPUT
ADD 1 TO WS-READ-CTR
IF IN-WINDOW-NUM IS NUMERIC
AND IN-WINDOW-NUM > 0
MOVE IN-WINDOW-NUM TO WS-REL-KEY
MOVE IN-TELLER-ID TO WF-TELLER-ID
MOVE IN-TELLER-NAME TO WF-TELLER-NAME
MOVE IN-BRANCH-CODE TO WF-BRANCH-CODE
MOVE IN-SHIFT-CODE TO WF-SHIFT-CODE
WRITE WINDOW-REC
INVALID KEY
ADD 1 TO WS-DUP-CTR
NOT INVALID KEY
ADD 1 TO WS-WRITE-CTR
END-WRITE
ELSE
ADD 1 TO WS-SKIP-CTR
END-IF
PERFORM 1000-READ-INPUT
END-PERFORM
CLOSE INPUT-FILE WINDOW-FILE
DISPLAY "RECORDS READ: " WS-READ-CTR
DISPLAY "RECORDS WRITTEN: " WS-WRITE-CTR
DISPLAY "DUPLICATES: " WS-DUP-CTR
DISPLAY "SKIPPED: " WS-SKIP-CTR
STOP RUN.
1000-READ-INPUT.
READ INPUT-FILE
AT END SET END-OF-INPUT TO TRUE
END-READ.
Exercise 11: Multi-File Processing Concept
Explain the balanced line algorithm (also called the matching-merge technique) in your own words. Your explanation should cover:
a) What problem does it solve? b) What precondition must the input files satisfy? c) How does the algorithm decide which file to read next? d) How are matched records, unmatched masters, and unmatched transactions handled differently?
Answer: a) The balanced line algorithm solves the problem of synchronizing two sorted files (typically a master file and a transaction file) to apply updates, detect matches, and identify orphan records in a single pass through both files.
b) Both files must be sorted on the same key field in the same order (typically ascending).
c) The algorithm compares the current key from each file. If the master key is lower, the master has no matching transaction (unmatched master) -- advance the master. If the transaction key is lower, the transaction has no matching master (unmatched transaction) -- advance the transaction. If the keys are equal, the records match -- process the update and advance both files.
d) Matched records are typically used to update the master with transaction data. Unmatched masters are written through unchanged (or reported as inactive). Unmatched transactions are written to an error/exception file (orphan transactions with no corresponding master).
Exercise 12: Random Access Account Lookup
Write a COBOL program that uses a relative file as a direct-access account lookup table. The relative file stores bank account summary records where the relative key is the last 4 digits of the account number (positions 7-10 of a 10-digit account number). The program should:
- Accept an account number from a transaction input file
- Extract the last 4 digits as the relative key
- Read the corresponding slot
- If found, display the account holder name and current balance
- If the slot is empty, display an error message
- Process all transactions and display a summary of found/not-found counts
Answer: See code/exercise-solutions.cob (EX12SOL)
Exercise 13: LINAGE-Based Report
Write a COBOL program that uses the LINAGE clause to produce a paginated account statement report. The report file should have: - 60 lines per logical page - Footing trigger at line 55 - 3-line top margin, 3-line bottom margin
The program should read account transactions and print: - A page heading with the bank name, report date, and page number - Detail lines showing transaction date, description, debit/credit amount, and running balance - When the LINAGE-COUNTER reaches the footing area, print a subtotal and advance to a new page - A final total line at the end
Answer: See code/exercise-solutions.cob (EX13SOL)
Exercise 14: Compare KSDS vs. RRDS
A banking application needs to store 50,000 customer records. The customer ID is a 10-digit number. Compare the trade-offs of using:
Option A: A VSAM KSDS with CUSTOMER-ID as the RECORD KEY Option B: A VSAM RRDS where the relative key is derived from the customer ID (e.g., using the last 5 digits)
Discuss the following for each option: access speed, storage efficiency, key collision handling, support for variable-length records, and suitability for sequential reporting.
Answer: - Access speed: RRDS is faster for random access (O(1) direct calculation vs. index traversal for KSDS). However, the difference is small for typical file sizes due to VSAM buffering. - Storage efficiency: KSDS is more storage-efficient because it only allocates space for records that exist. RRDS pre-allocates all slots (if using last 5 digits, that is 100,000 slots, but only 50,000 occupied -- 50% wasted space). - Key collision: KSDS has no collision problem since the full 10-digit key is unique. RRDS using the last 5 digits risks collisions (two different customer IDs could map to the same slot). Collision resolution adds complexity. - Variable-length records: KSDS supports them; RRDS does not (fixed-length only). - Sequential reporting: Both support sequential access, but KSDS reads records in key order naturally, while RRDS reads in slot number order (which may include empty slots to skip).
Conclusion: KSDS is the better choice for this scenario due to the large key space and collision risk with RRDS.
Exercise 15: DELETE and REWRITE Operations
Write a COBOL paragraph that performs the following operations on a relative file opened I-O with DYNAMIC access:
- Read slot 150 randomly. If found, display the record.
- If the record's status field is 'C' (closed), DELETE the record.
- If the record's status field is 'A' (active), update the balance field by adding a transaction amount, then REWRITE the record.
- Handle all error conditions with appropriate file status checking.
2000-PROCESS-SLOT-150.
MOVE 150 TO WS-REL-KEY
READ ACCOUNT-FILE INTO WS-ACCOUNT-REC
INVALID KEY
DISPLAY "SLOT 150 IS EMPTY"
DISPLAY "FILE STATUS: " WS-FILE-STATUS
GO TO 2000-EXIT
END-READ
DISPLAY "FOUND: " WS-ACCT-NAME " BAL=" WS-BALANCE
EVALUATE WS-ACCT-STATUS
WHEN 'C'
DELETE ACCOUNT-FILE
INVALID KEY
DISPLAY "DELETE FAILED: "
WS-FILE-STATUS
NOT INVALID KEY
DISPLAY "SLOT 150 DELETED"
END-DELETE
WHEN 'A'
ADD WS-TRANS-AMOUNT TO WS-BALANCE
REWRITE ACCOUNT-REC FROM WS-ACCOUNT-REC
INVALID KEY
DISPLAY "REWRITE FAILED: "
WS-FILE-STATUS
NOT INVALID KEY
DISPLAY "SLOT 150 UPDATED"
END-REWRITE
WHEN OTHER
DISPLAY "UNKNOWN STATUS: "
WS-ACCT-STATUS
END-EVALUATE.
2000-EXIT.
EXIT.
Exercise 16: Multi-File Coordinated Processing
Explain why you must be careful about the order of OPEN and CLOSE statements when a program processes multiple files simultaneously. Specifically, address:
a) What happens if you open an output file before opening its corresponding input file, and the program fails between the two OPEN statements? b) Why should you close output files before closing input files in most batch programs? c) How does the FILE STATUS field help coordinate multi-file error handling?
Answer: a) If the output file is opened (and potentially truncated/created) before the input file is successfully opened, you may destroy existing output data while being unable to read the input. If the program ABENDs, the output file may be empty or incomplete with no way to recover.
b) Closing output files first ensures that all buffered records are flushed to disk and the file is properly completed (with any trailer records, end-of-file markers, etc.) before releasing input resources. If the program closes the input file first and then fails while closing the output, the output may be incomplete.
c) FILE STATUS provides a two-character return code after every I/O operation. In multi-file processing, you should check the status after each OPEN to ensure all files are accessible before proceeding. If any file fails to open, you can close the already-opened files cleanly and terminate gracefully, rather than proceeding with a partial set of files.
Tier 3: Apply (Exercises 17-22)
Exercise 17: Debug This Program
The following program attempts to create a relative file of branch records, but it produces incorrect results. Find and fix all bugs.
IDENTIFICATION DIVISION.
PROGRAM-ID. BUGGY01.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT BRANCH-FILE ASSIGN TO BRCHFILE
ORGANIZATION IS RELATIVE
ACCESS MODE IS SEQUENTIAL
RELATIVE KEY IS WS-REL-KEY
FILE STATUS IS WS-STATUS.
DATA DIVISION.
FILE SECTION.
FD BRANCH-FILE.
01 BRANCH-REC.
05 BR-REL-KEY PIC 9(4).
05 BR-NAME PIC X(30).
05 BR-CITY PIC X(20).
05 FILLER PIC X(26).
WORKING-STORAGE SECTION.
01 WS-REL-KEY PIC 9(4).
01 WS-STATUS PIC XX.
PROCEDURE DIVISION.
OPEN OUTPUT BRANCH-FILE
MOVE 1 TO BR-REL-KEY
MOVE "MAIN STREET" TO BR-NAME
MOVE "NEW YORK" TO BR-CITY
WRITE BRANCH-REC
MOVE 5 TO BR-REL-KEY
MOVE "PARK AVENUE" TO BR-NAME
MOVE "NEW YORK" TO BR-CITY
WRITE BRANCH-REC
CLOSE BRANCH-FILE
STOP RUN.
Answer: There are three bugs:
Bug 1: The program sets BR-REL-KEY (the field inside the FD record) instead of WS-REL-KEY (the RELATIVE KEY in WORKING-STORAGE). The relative key used for positioning is WS-REL-KEY, not a field in the record itself.
Fix: Change MOVE 1 TO BR-REL-KEY to MOVE 1 TO WS-REL-KEY, and MOVE 5 TO BR-REL-KEY to MOVE 5 TO WS-REL-KEY.
Bug 2: With ACCESS MODE IS SEQUENTIAL, writing record 1 and then record 5 will fail because sequential WRITE writes records in consecutive order (1, 2, 3...). You cannot skip to slot 5 in sequential mode. To write to non-consecutive slots, you need ACCESS MODE IS RANDOM.
Fix: Change ACCESS MODE IS SEQUENTIAL to ACCESS MODE IS RANDOM.
Bug 3: No INVALID KEY checking on the WRITE statements. If a write fails (e.g., duplicate slot), the program silently continues.
Fix: Add INVALID KEY / NOT INVALID KEY clauses to each WRITE.
Exercise 18: Master File Update with Relative File
Write a complete COBOL program that performs a master file update using a relative file. The relative file stores loan account records (slot number = loan number, 1 through 9999). The transaction file contains records with: - Transaction Code: PIC X(1) ('A'=Add, 'U'=Update, 'D'=Delete) - Loan Number: PIC 9(4) - Borrower Name: PIC X(30) - Loan Amount: PIC 9(7)V99 - Interest Rate: PIC 9(2)V999 - Payment Due Date: PIC 9(8) (YYYYMMDD) - Filler: PIC X(28) (total = 80 bytes)
For Add: Write a new record to the slot; report error if slot is occupied. For Update: Read the existing record, apply changes, REWRITE; report error if slot is empty. For Delete: DELETE the record; report error if slot is empty.
Display statistics at the end: adds, updates, deletes, and errors for each type.
Hint: Use ACCESS MODE IS RANDOM and OPEN I-O. Remember to set WS-REL-KEY to the loan number before each operation. Check FILE STATUS after every I/O.
Exercise 19: Dynamic Access Browse
Write a COBOL program that implements a "browse" feature on a relative file of safe deposit box assignments. The program should:
- Accept a starting box number from the user (ACCEPT statement or input file)
- Use START to position the file at or after that box number
- Read and display the next 10 occupied boxes sequentially
- If fewer than 10 occupied boxes remain, display what is available and indicate end of file
Use ACCESS MODE IS DYNAMIC. Show proper use of START, sequential READ, and file status checking.
Hint: Remember that START positions the file for subsequent sequential READs. The READ NEXT statement retrieves records in sequence after a START. Empty slots are automatically skipped during sequential reads.
Exercise 20: Checkpoint/Restart Design
A long-running batch program processes 5 million loan payment records against a relative file of loan accounts. Design (and write the key paragraphs for) a checkpoint/restart mechanism that:
- Every 50,000 transactions, writes a checkpoint record to a checkpoint file containing: the current transaction count, the last transaction key processed, and the current timestamp
- If the program is restarted after a failure, reads the last checkpoint record and resumes processing from the next unprocessed transaction
- Uses a status flag to distinguish between a fresh run and a restart run
Hint: The checkpoint file can be a simple sequential file. On restart, read the last record to determine where to resume. You will need to PERFORM a skip-forward loop to bypass already-processed transactions.
Exercise 21: EXTEND Mode Appending
Write a COBOL program that appends new daily transaction summary records to an existing relative file. The program should:
- Open the relative file in EXTEND mode with SEQUENTIAL access
- Read a sequential input file of daily summaries
- Write each record to the next available slot in the relative file
- Handle the case where the relative file reaches its maximum capacity
Explain why EXTEND mode requires SEQUENTIAL access and why you cannot use RANDOM access with EXTEND.
Answer: EXTEND mode positions the file pointer after the last existing record and allows sequential writes from that point. RANDOM access conflicts with EXTEND because random access requires specifying a slot number, which contradicts the "append after last record" semantics. With EXTEND, the system automatically assigns the next sequential slot number.
Exercise 22: Multi-File Balanced Line Processing
Write a complete COBOL program that implements the balanced line algorithm to update a master customer relative file using a sorted transaction file. The master file has 9,999 slots (customer number = slot number). The transaction file is sorted by customer number.
The program should: - Read both files in parallel using the balanced line technique - For matching records: apply the transaction (update balance) - For unmatched master records: write them unchanged to a new master file - For unmatched transactions: write them to an exception file - Display counts of matches, unmatched masters, unmatched transactions, and total records processed
Hint: Since the master is a relative file, you must read it sequentially. The trick is to handle the comparison: if the master's customer number (from the relative key) is less than the transaction's customer number, advance the master. If greater, the transaction is unmatched. If equal, apply the update.
Tier 4: Analyze (Exercises 23-29)
Exercise 23: Performance Analysis
A financial institution uses a relative file to store daily ATM transaction summaries. The file has 10,000 slots (one per ATM terminal, numbered 0001-9999). During peak hours, the system processes 500 random lookups per second.
a) Calculate the theoretical I/O advantage of relative files over indexed files for this workload. Assume each RRDS random read requires 1 physical I/O, while each KSDS random read requires 2.5 I/Os on average (index traversal + data read).
b) If each physical I/O takes 2 milliseconds, calculate the total I/O time per second for each file type.
c) Under what conditions would the indexed file actually perform comparably? (Hint: consider VSAM buffering and local shared resources.)
d) The institution is considering switching to a KSDS for flexibility. What non-performance factors should they evaluate?
Hint: Consider buffer pool hit ratios, CI/CA splits, and the operational overhead of managing each file type.
Exercise 24: Slot Allocation Strategy
A bank needs to store 50,000 checking account records in a relative file. Account numbers range from 1000000000 to 9999999999 (10-digit numbers). Design and evaluate three different strategies for mapping account numbers to relative record slots:
a) Direct mapping: Use the full account number as the relative key (slot = account number) b) Modulo mapping: slot = (account-number MOD 50000) + 1 c) Hash mapping: slot = hash-function(account-number), where the hash produces values 1-65000
For each strategy, analyze: storage requirements, collision probability, access speed, and implementation complexity. Recommend the best approach and explain why.
Hint: Direct mapping with 10-digit numbers would require a file with 10 billion slots. That is clearly impractical. Focus on analyzing the trade-offs of modulo and hash approaches, including how to handle collisions.
Exercise 25: Debug a Complex Multi-File Program
The following program is supposed to read a transaction file and update two relative files (a checking account file and a savings account file) based on the transaction type. It compiles but produces incorrect results. Identify all bugs.
PROCEDURE DIVISION.
0000-MAIN.
OPEN I-O CHECKING-FILE
OPEN I-O SAVINGS-FILE
OPEN INPUT TRANS-FILE
PERFORM 1000-READ-TRANS
PERFORM UNTIL END-OF-TRANS
EVALUATE TRANS-TYPE
WHEN 'C'
MOVE TRANS-ACCT TO WS-CHK-KEY
READ CHECKING-FILE
ADD TRANS-AMOUNT TO CHK-BALANCE
REWRITE CHECKING-REC
WHEN 'S'
MOVE TRANS-ACCT TO WS-SAV-KEY
READ SAVINGS-FILE
ADD TRANS-AMOUNT TO SAV-BALANCE
REWRITE SAVINGS-REC
WHEN OTHER
DISPLAY "INVALID TYPE: " TRANS-TYPE
END-EVALUATE
PERFORM 1000-READ-TRANS
END-PERFORM
CLOSE CHECKING-FILE
SAVINGS-FILE
TRANS-FILE
STOP RUN.
Hint: Look for missing error handling, missing INTO clauses, the interaction between READ and REWRITE with relative files, and what happens when a transaction references a nonexistent account. There are at least 4 distinct issues.
Exercise 26: Designing a File Recovery Procedure
A critical relative file storing loan payment records has been corrupted -- 200 of its 5,000 slots contain garbled data (detected by validation checks on known fields). Design a recovery procedure that:
- Reads the corrupted relative file sequentially and identifies which slots are damaged
- Reads a backup sequential file (yesterday's export) to obtain clean data for the damaged slots
- Reconstructs the damaged slots using random REWRITE operations
- Validates the repaired file by comparing record counts and hash totals
- Produces an audit report of all repairs
Describe the algorithm and write pseudocode or COBOL code for the key paragraphs.
Hint: You will need DYNAMIC access on the relative file (sequential read to find damage, random REWRITE to repair). The backup file must be sorted by slot number to enable efficient lookup.
Exercise 27: LINAGE vs. Manual Page Control
Rewrite the following manual page-control logic using the LINAGE clause instead. Identify which lines of manual code become unnecessary when LINAGE handles page overflow automatically.
01 WS-LINE-COUNT PIC 99 VALUE 0.
01 WS-PAGE-COUNT PIC 999 VALUE 0.
01 WS-MAX-LINES PIC 99 VALUE 55.
...
2000-WRITE-DETAIL.
IF WS-LINE-COUNT >= WS-MAX-LINES
PERFORM 3000-PAGE-BREAK
END-IF
WRITE PRINT-REC FROM WS-DETAIL-LINE
AFTER ADVANCING 1 LINE
ADD 1 TO WS-LINE-COUNT.
3000-PAGE-BREAK.
WRITE PRINT-REC FROM WS-HEADING
AFTER ADVANCING PAGE
MOVE 1 TO WS-LINE-COUNT
ADD 1 TO WS-PAGE-COUNT.
Hint: With LINAGE, you replace the manual line counter with LINAGE-COUNTER, and you can use the FOOTING AT clause to trigger page footings automatically. The WRITE... AT END-OF-PAGE clause replaces the manual overflow check.
Exercise 28: Relative File Capacity Planning
A regional bank processes 2,000 new loan applications daily. Each approved loan is stored in a relative file where the slot number is derived from the 6-digit loan number. Analyze the following capacity questions:
a) If the loan number starts at 000001 and increments sequentially, how many years until the relative file reaches its maximum 999,999 slots at the current growth rate?
b) If 30% of loans are paid off and their slots are deleted each year, what is the effective growth rate?
c) Design a slot reuse strategy that reclaims deleted slots for new loans. What are the trade-offs compared to always using the next sequential number?
d) What happens when the relative file reaches capacity? Design a file migration strategy.
Hint: For part (c), consider maintaining a "free list" -- a separate data structure that tracks available slots for reuse.
Exercise 29: Cross-Platform Relative File Considerations
A COBOL application that uses relative files is being migrated from z/OS (VSAM RRDS) to a Linux server (GnuCOBOL). Identify and discuss at least five technical differences that must be addressed during the migration:
Hint: Consider file system differences (VSAM vs. POSIX), record delimiters, empty slot handling, maximum file sizes, endianness of numeric fields, and file status code differences.
Tier 5: Create (Exercises 30-34)
Exercise 30: Complete ATM Transaction System
Design and write a complete COBOL program that simulates an ATM transaction processing system. The system uses a relative file to store account records (slot = last 4 digits of account number, up to 9,999 accounts). The program must:
- Read a batch of ATM transactions (withdrawal, deposit, balance inquiry, transfer)
- For withdrawals: check sufficient funds, apply daily withdrawal limit ($500), deduct amount, update transaction count
- For deposits: add amount, update transaction count
- For balance inquiries: read and display the balance (no update)
- For transfers: debit one account and credit another atomically (both must succeed or neither)
- Write all processed transactions to an audit trail file
- Produce a daily summary report using the LINAGE clause with page headings and account subtotals
Include complete error handling, file status checking, and statistics display.
Hint: For transfers, read both accounts first to verify they exist and have sufficient funds before writing either update. If the first REWRITE succeeds but the second fails, you must reverse the first update (compensating transaction).
Exercise 31: Multi-Branch Consolidation System
A bank has 25 branches, each maintaining its own relative file of daily transactions (one file per branch, up to 1,000 slots per file). Design and write a COBOL program that:
- Opens all 25 branch files (use an array of file names and dynamic OPEN)
- Reads each branch file sequentially
- Consolidates all transactions into a single master sequential file, sorted by account number
- Detects and reports cross-branch duplicate account numbers
- Produces a branch-by-branch summary report showing record counts and total balances
Since COBOL cannot dynamically declare files, discuss how you would handle 25 files. Propose an architecture that processes them in batches if the system cannot open all 25 simultaneously.
Hint: One practical approach is to process the 25 files in groups (e.g., 5 at a time), merging each group's output into an intermediate file, then merging the intermediates. Alternatively, use a single program that processes one file at a time and appends to the consolidated output, followed by a sort step.
Exercise 32: Relative File-Based Cache System
Design and write a COBOL program that implements a simple cache using a relative file. The cache stores the 1,000 most recently accessed customer records (from a larger KSDS master file). The relative file has 1,000 slots, and the cache uses a hash of the customer ID to determine the slot.
The program should: 1. Accept a customer ID lookup request 2. Calculate the hash: slot = (customer-ID MOD 1000) + 1 3. Read the relative file slot; if it contains the requested customer, return it (cache hit) 4. If the slot is empty or contains a different customer (cache miss), read the KSDS master, WRITE or REWRITE the cache slot, and return the record 5. Track and display cache hit/miss statistics
Discuss the limitations of this simple hashing approach and how collisions reduce cache effectiveness.
Hint: This is a direct-mapped cache. A customer ID that hashes to an occupied slot will evict the existing entry. More sophisticated approaches (set-associative caching) would use multiple slots per hash bucket, but that adds significant complexity in COBOL.
Exercise 33: Loan Payment Processing Pipeline
Design and write a complete batch processing pipeline (multiple COBOL programs coordinated by JCL) for monthly loan payment processing:
Program 1 (LNVALID): Validate incoming payment records, reject invalid payments, write valid payments to a work file.
Program 2 (LNUPDATE): Apply validated payments to the loan master relative file. Update principal balance, calculate interest, update payment history. Handle overpayments and underpayments.
Program 3 (LNREPORT): Read the updated loan master relative file and produce a monthly loan status report using the LINAGE clause. Include page headings, detail lines, delinquency flags for past-due loans, and a grand total summary.
Write the three COBOL programs and the JCL to run them in sequence.
Hint: Program 2 is the most complex. For each payment, calculate interest = (outstanding principal * annual rate / 12). The payment is applied first to interest, then to principal. If the payment exceeds the outstanding balance, the excess is an overpayment to be refunded.
Exercise 34: File Organization Migration Tool
Write a COBOL utility program that converts between file organizations. The program should accept a parameter indicating the conversion direction:
- S2R: Sequential to Relative (load a sequential file into a relative file)
- R2S: Relative to Sequential (export a relative file to a sequential file)
- I2R: Indexed (KSDS) to Relative (create a relative file from an indexed file)
- R2I: Relative to Indexed (create an indexed file from a relative file)
For each direction, the program must: 1. Handle record format differences (the relative file adds/removes the slot number) 2. Report record counts for input, output, skipped, and error records 3. Validate that the target file was created correctly by reading it back and comparing counts
Write the complete program with all four conversion modes.
Hint: Use EVALUATE on the conversion-direction parameter to branch to the appropriate processing section. Each section opens the appropriate input and output files and performs the conversion. The R2S conversion must handle empty slots (skip them). The S2R conversion must decide how to assign slot numbers (sequential? based on a key field?).