Chapter 4 Exercises: The WORKING-STORAGE and LOCAL-STORAGE Sections
These exercises are organized in five tiers of increasing difficulty. Complete all exercises in a tier before moving to the next. Solutions for selected exercises are provided in code/exercise-solutions.cob.
Tier 1: Fundamentals (Exercises 1-7)
These exercises test your basic understanding of WORKING-STORAGE definitions, level numbers, and VALUE clauses.
Exercise 1: Student Record Definition
Define a WORKING-STORAGE record for a student with the following fields: - Student ID (9 characters, alphanumeric) - Student name with last name (20 chars), first name (15 chars), and middle initial (1 char) - GPA (1 digit before decimal, 2 after) - Enrollment status (1 character)
Include 88-level conditions on the GPA field for honors (3.50-4.00), dean's list (3.00-3.49), good standing (2.00-2.99), and academic probation (below 2.00). Include 88-levels on status for enrolled, graduated, withdrawn, and suspended.
Exercise 2: Level Number Identification
For each of the following level numbers, state its purpose and whether it allocates storage:
a) Level 01 b) Level 05 c) Level 49 d) Level 66 e) Level 77 f) Level 88
Exercise 3: Payment Method Conditions
Define a PIC X(02) field called WS-PAYMENT-METHOD with 88-level conditions for:
- Cash ('CA')
- Check ('CK')
- Credit Card ('CC')
- Debit Card ('DC')
- Wire Transfer ('WT')
- ACH ('AC')
Also define composite conditions: WS-PAY-CARD-TYPE (credit or debit), WS-PAY-ELECTRONIC (credit, debit, wire, ACH), WS-PAY-PHYSICAL (cash or check), and WS-PAY-VALID (any of the six valid values).
Exercise 4: VALUE Clause Errors
Identify what is wrong with each of the following definitions:
a) 01 WS-COUNTER PIC 9(03) VALUE 'ABC'.
b) 01 WS-NAME PIC X(05) VALUE 'ALEXANDER'.
c) 01 WS-GROUP.
05 WS-NUM PIC 9(03) VALUE ZEROS.
05 WS-ALPHA PIC X(05) VALUE ZEROS.
d) 01 WS-AMOUNT PIC 9(03)V99 VALUE 12345.67.
e) 77 WS-RECORD.
05 WS-FIELD PIC X(05).
Exercise 5: Date REDEFINES
Create a date field defined as PIC 9(08) with a REDEFINES that breaks it into year (PIC 9(04)), month (PIC 9(02)), and day (PIC 9(02)). Add a second REDEFINES for an alphanumeric view. Include 88-level conditions on the month for valid months (01-12) and on the day for valid days (01-31). Also add 88-levels for quarter classifications (Q1: months 01-03, Q2: months 04-06, Q3: months 07-09, Q4: months 10-12).
Exercise 6: Figurative Constants
What value does each field contain after these statements?
01 WS-FIELD-A PIC X(10).
01 WS-FIELD-B PIC 9(05).
01 WS-FIELD-C PIC X(08).
01 WS-FIELD-D PIC X(06).
01 WS-FIELD-E PIC X(10).
MOVE SPACES TO WS-FIELD-A
MOVE ZEROS TO WS-FIELD-B
MOVE HIGH-VALUES TO WS-FIELD-C
MOVE LOW-VALUES TO WS-FIELD-D
MOVE ALL '*' TO WS-FIELD-E
Exercise 7: Group Item Size Calculation
Calculate the total size in bytes of the following record:
01 WS-EMPLOYEE.
05 WS-EMP-ID PIC X(06).
05 WS-EMP-NAME.
10 WS-LAST PIC X(20).
10 WS-FIRST PIC X(15).
10 WS-MI PIC X(01).
05 WS-EMP-SALARY PIC 9(07)V99.
05 WS-EMP-DEPT PIC X(04).
05 WS-EMP-STATUS PIC X(01).
Also state the byte offset (starting from 0) for each elementary item.
Tier 2: Applied Knowledge (Exercises 8-14)
These exercises require you to apply concepts to realistic scenarios.
Exercise 8: Product Inventory Record
Design a complete WORKING-STORAGE record for a product inventory system. Include: - Product ID and description (name and category with 88-levels) - Pricing section (unit cost, selling price, margin percentage) - Stock information (quantity on hand, quantity on order, reorder point, stock status with 88-levels) - Supplier information (supplier ID, name, lead time in days)
Use proper level numbers (05/10/15), naming conventions (WS- prefix), and 88-level conditions for category codes and stock status.
Exercise 9: INITIALIZE Behavior Prediction
Given this record definition:
01 WS-ORDER.
05 WS-ORD-ID PIC X(08).
05 WS-ORD-DATE PIC 9(08).
05 WS-ORD-AMOUNT PIC 9(07)V99.
05 FILLER PIC X(02) VALUE '--'.
05 WS-ORD-STATUS PIC X(01) VALUE 'N'.
What are the values of each field after each of these operations? Answer for all five fields each time.
a) INITIALIZE WS-ORDER
b) MOVE SPACES TO WS-ORDER
c) MOVE ZEROS TO WS-ORDER
d) INITIALIZE WS-ORDER REPLACING ALPHANUMERIC DATA BY '*'
e) INITIALIZE WS-ORDER ALL TO VALUE
Exercise 10: REDEFINES Validation
Which of the following REDEFINES definitions are valid? For each invalid one, explain why.
a) 01 WS-DATE PIC 9(08).
01 WS-DATE-X REDEFINES WS-DATE PIC X(08).
b) 05 WS-CODE PIC X(03).
01 WS-CODE-R REDEFINES WS-CODE PIC 9(03).
c) 01 WS-FIELD-A PIC X(10).
01 WS-FIELD-B PIC X(05).
01 WS-FIELD-C REDEFINES WS-FIELD-A PIC X(10).
d) 01 WS-TABLE OCCURS 10 TIMES PIC X(05).
01 WS-TABLE-R REDEFINES WS-TABLE PIC X(50).
e) 77 WS-STANDALONE PIC X(08).
77 WS-STAND-R REDEFINES WS-STANDALONE PIC 9(08).
Exercise 11: Multi-Format Transaction Record
Create a transaction record with a common header (transaction type PIC X(01) and date PIC 9(08)) followed by a data area of 80 bytes. Define REDEFINES for three transaction types:
- Sale (type 'S'): product ID (10), quantity (5 digits), price (7.99), tax (5.99), total (7.99), cashier ID (6)
- Return (type 'R'): original transaction reference (12), product ID (10), quantity (5 digits), refund amount (7.99), reason code (2) with 88-levels
- Exchange (type 'X'): original product ID (10), new product ID (10), price difference (signed 7.99), authorization code (8)
Use FILLER to pad each REDEFINES to exactly the same size as the original record.
Exercise 12: 88-Level EVALUATE Pattern
Write a set of 88-level conditions for an HTTP status code field (PIC 9(03)) and then write an EVALUATE TRUE statement that displays an appropriate message for each category:
- 200-299: Success codes (with specific 88s for 200 OK, 201 Created, 204 No Content)
- 300-399: Redirect codes (with specific 88 for 301 Moved Permanently)
- 400-499: Client error codes (with specific 88s for 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found)
- 500-599: Server error codes (with specific 88s for 500 Internal Error, 502 Bad Gateway, 503 Service Unavailable)
Exercise 13: Table with REDEFINES Initialization
Create a lookup table for the 12 zodiac signs, where each entry contains: - Sign name (12 characters) - Start month (2 digits) - Start day (2 digits) - End month (2 digits) - End day (2 digits)
Use the VALUE/REDEFINES pattern to pre-load the data at compile time, then write PROCEDURE DIVISION code that accepts a birth month and day and displays the corresponding zodiac sign.
Exercise 14: WORKING-STORAGE Organization Review
The following WORKING-STORAGE is poorly organized. Rewrite it using the organizational conventions described in this chapter (constants first, then flags, counters, work fields, etc.). Use proper naming conventions and add 88-level conditions where appropriate.
WORKING-STORAGE SECTION.
01 TOTAL PIC 9(07)V99.
01 TAX-RATE PIC V99 VALUE .08.
01 FLAG PIC X VALUE 'N'.
01 REC-CTR PIC 999 VALUE 0.
01 AMOUNT PIC 9(05)V99.
01 NAME-FLD PIC X(25).
01 ERR-CTR PIC 999 VALUE 0.
01 MAX-RECS PIC 999 VALUE 500.
01 DATE-FLD PIC 9(08).
01 STATUS-CD PIC X.
01 DISPLAY-AMT PIC $$,$$9.99.
Tier 3: Problem Solving (Exercises 15-21)
These exercises require creative application of concepts to solve non-trivial problems.
Exercise 15: State Tax Rate Lookup Table
Create a lookup table of US state sales tax rates using the VALUE/REDEFINES pattern. Include at least 9 states. Each entry should contain a 2-character state code and a tax rate (PIC 9V9(04)). Write PROCEDURE DIVISION code that:
- Accepts a state code
- Searches the table for a matching entry
- Displays the tax rate if found, or an error message if not found
- Calculates the tax on a given purchase amount
Exercise 16: Recursive Call Counter
Write a main program and a subprogram where the subprogram has both WORKING-STORAGE and LOCAL-STORAGE sections. The main program calls the subprogram 10 times, passing an incrementing number each time. The subprogram should:
- In WORKING-STORAGE: maintain a running total of all numbers received
- In LOCAL-STORAGE: attempt to maintain a running total (to demonstrate it resets)
- Display both totals on each call to illustrate the persistence difference
Exercise 17: Complex Record with Validation
Design WORKING-STORAGE for a medical patient record that includes: - Patient demographics (name, DOB, gender with 88-levels, blood type with 88-levels including valid types and Rh factor) - Insurance information (provider, policy number, group number, coverage type with 88-levels) - Allergies (table of up to 10 allergies, each with name and severity with 88-levels) - Current medications (table of up to 15 medications with name, dosage, frequency with 88-levels) - Emergency contact (name, relationship with 88-levels, phone)
Write a validation paragraph that checks all 88-level conditions and counts the number of validation errors.
Exercise 18: Paycheck Program WORKING-STORAGE
Design the complete WORKING-STORAGE for a paycheck printing program. Include all seven organizational sections (constants, flags, counters, accumulators, work fields, input layout, display fields). The program must handle:
- Hourly and salaried employees (different calculation paths)
- Federal tax, state tax, FICA, and Medicare deductions
- Overtime at 1.5x for hourly employees over 40 hours
- Report header, detail, and summary lines with proper formatting
Exercise 19: REDEFINES for Report Line Variants
A report has three types of lines: header, detail, and total. All lines must be exactly 132 characters (standard print width). Create a single 01-level record of 132 characters with REDEFINES for each line type:
- Header: report title (centered in 50 chars), date (10 chars), page number (5 chars), fill
- Detail: employee ID (8), name (25), department (10), hours (5), rate (8), gross pay (12), net pay (12), fill
- Total: label (25), total gross (12), total deductions (12), total net (12), fill
Write code to format and display one of each line type.
Exercise 20: LOCAL-STORAGE for String Builder
Write a subprogram that acts as a string builder. It accepts a string fragment and an action code ('A' for append, 'R' for reset, 'G' for get/return). Use WORKING-STORAGE to maintain the accumulated string across calls, and LOCAL-STORAGE for the per-call work fields. Demonstrate by calling it multiple times to build a sentence word by word.
Exercise 21: Nested OCCURS with Initialization
Define a WORKING-STORAGE structure for a school schedule with: - 5 school days - 8 periods per day - Each period has: course code (6), course name (25), teacher name (20), room number (4)
Write code that: 1. Initializes the entire table 2. Populates Monday's schedule with 8 courses 3. Copies Monday's schedule to Tuesday (demonstrating group-level OCCURS operations) 4. Displays the full schedule for both days
Tier 4: Integration Challenges (Exercises 22-28)
These exercises integrate multiple concepts into larger programs.
Exercise 22: INITIALIZE REPLACING for Report Defaults
Create a report record with numeric and alphanumeric fields. Write code that demonstrates three different initialization strategies: 1. Standard INITIALIZE (spaces/zeros) 2. INITIALIZE REPLACING ALPHANUMERIC BY 'N/A' (for "not available" defaults) 3. INITIALIZE REPLACING NUMERIC BY -1 (for "not computed" sentinel values)
Show the output of each strategy and explain when each would be appropriate in a real application.
Exercise 23: Complete Data Validation Framework
Design a WORKING-STORAGE structure for a comprehensive data validation framework. Include: - An input record area - A validation rules table (using OCCURS) with rule ID, field name, rule type (88-levels for: required, numeric, range-check, value-list), and parameters - An error message table (using OCCURS) to accumulate validation failures - Counters for rules checked, rules passed, and rules failed - A validation result flag with 88-levels
Write the validation paragraph that iterates through the rules table and validates an input record.
Exercise 24: Multi-Level Control Break Accumulators
Design WORKING-STORAGE for a sales report with three control break levels: - Level 1: Salesperson (name, ID) - Level 2: Region (code, name) - Level 3: Division (code, name)
Each level needs: subtotal accumulators (quantity, amount, tax), record counts, and hold fields for break detection. Also define grand total accumulators. Include display formatting fields for all three subtotal lines and the grand total line.
Exercise 25: REDEFINES-Based Record Parser
Design WORKING-STORAGE for a program that reads a fixed-length record where the first 2 characters determine the record type, and the remaining 98 characters have a different layout for each type. Define at least 4 record types with different field structures. Include:
- A raw input area (100 bytes)
- REDEFINES for each record type
- A record type indicator with 88-levels
- Error handling fields for unrecognized record types
- Counters for each record type processed
Write the record-type dispatching logic using EVALUATE.
Exercise 26: Working-Storage Memory Map
Given the following WORKING-STORAGE, calculate and document: - The byte offset of every elementary item from the start of its 01-level group - The total size of each 01-level item - The total WORKING-STORAGE size
01 WS-HEADER.
05 WS-H-TYPE PIC X(02).
05 WS-H-SEQ PIC 9(06).
05 WS-H-DATE PIC 9(08).
05 WS-H-FILLER PIC X(04).
01 WS-DETAIL.
05 WS-D-ID PIC X(10).
05 WS-D-NAME PIC X(30).
05 WS-D-AMOUNTS.
10 WS-D-AMT1 PIC S9(07)V99.
10 WS-D-AMT2 PIC S9(07)V99.
10 WS-D-AMT3 PIC S9(05)V99.
05 WS-D-CODES.
10 WS-D-CODE OCCURS 5 TIMES PIC X(03).
05 WS-D-STATUS PIC X(01).
01 WS-SUMMARY.
05 WS-S-TOTALS.
10 WS-S-TOT OCCURS 3 TIMES PIC 9(11)V99.
05 WS-S-COUNT PIC 9(07).
05 WS-S-DATE PIC 9(08).
Exercise 27: Condition-Name-Driven State Machine
Design WORKING-STORAGE for a simple order processing state machine. Define a state field with 88-levels for: NEW, VALIDATED, PRICED, APPROVED, SHIPPED, DELIVERED, COMPLETED, CANCELLED, ERROR. Define valid state transitions (e.g., NEW can go to VALIDATED or CANCELLED, but not directly to SHIPPED). Write an EVALUATE-based state transition procedure that:
- Checks if the requested transition is valid
- Logs the transition (from-state, to-state, timestamp) in a transition history table (OCCURS)
- Displays an error if the transition is invalid
Exercise 28: Complete Report Writer WORKING-STORAGE
Design the complete WORKING-STORAGE for a report-writing program that produces a customer account statement. Include:
- Page control fields (page number, line count, lines per page, page overflow flag)
- Date/time fields for the report header
- Customer information area
- Transaction detail area with totals
- Report line definitions (page header, column headers, detail line, subtotal line, page footer, grand total line) -- all exactly 132 characters
- Running totals for debits, credits, and balance
- Control fields for page breaks and end-of-report
Tier 5: Expert Challenges (Exercises 29-35)
These exercises push the boundaries of WORKING-STORAGE design and COBOL data definition.
Exercise 29: Self-Describing Record Structure
Design a WORKING-STORAGE structure for a self-describing data format where: - The first 4 bytes contain the total record length - The next 2 bytes contain the number of fields - Each field is preceded by a 2-byte field type code, a 2-byte field length, and then the field data
Use REDEFINES to overlay the raw byte area with structured field descriptors. Write parsing logic that reads each field dynamically based on the embedded type and length information.
Exercise 30: Calendar System
Design complete WORKING-STORAGE for a calendar utility that: - Stores a full year calendar (12 months, up to 31 days each, with day-of-week indicators) - Uses OCCURS for the month/day structure - Includes a REDEFINES-initialized table of month names and days-per-month - Has work fields for leap year calculation - Has 88-levels for day-of-week (Monday through Sunday, plus WEEKDAY/WEEKEND) - Includes formatted output lines for displaying a month in calendar format (7 columns, one per day of week)
Write the logic to populate the calendar for any given year and display any requested month.
Exercise 31: Dynamic Table Management
Design WORKING-STORAGE for a sorted table that supports dynamic insertion, deletion, and searching: - Maximum 200 entries, each with key (PIC X(10)) and data (PIC X(40)) - A current-count field - Work fields for binary search - Work fields for insertion (shifting elements down) - Work fields for deletion (shifting elements up) - Performance counters (comparisons made, shifts performed)
Write the insertion paragraph that maintains the table in sorted order by key, shifting existing entries as needed.
Exercise 32: WORKING-STORAGE Refactoring Challenge
The following poorly-designed WORKING-STORAGE has multiple problems (duplicated constants, missing 88-levels, inconsistent naming, poor organization, unsafe REDEFINES, missing initializations). Identify all problems, then rewrite the entire section following best practices:
WORKING-STORAGE SECTION.
01 EOF-SW PIC X VALUE 'N'.
01 RECORD-AREA PIC X(100).
01 REC-TYPED REDEFINES RECORD-AREA.
05 R-TYPE PIC XX.
05 R-DATA PIC X(98).
01 REC-TYPED-2 REDEFINES RECORD-AREA.
05 FILLER PIC XX.
05 R2-NAME PIC X(30).
05 R2-AMT PIC 9(5)V99.
05 R2-FILLER PIC X(61).
01 TAX-RATE PIC V99 VALUE .06.
01 TAXRATE PIC V99 VALUE .06.
01 amt-total PIC 9(9)V99.
01 CTR1 PIC 999 VALUE 0.
01 CTR2 PIC 999 VALUE 0.
01 TMP PIC X(50).
01 BIG-REC.
05 B-1 PIC X(5000).
05 B-2 PIC X(5000).
01 WORK-DATE PIC 9(6).
01 WORK-DATE-R REDEFINES WORK-DATE.
05 WD-MM PIC 99.
05 WD-DD PIC 99.
05 WD-YY PIC 99.
01 DISPLAY-LINE PIC X(80).
Exercise 33: Cross-Reference Generator Data
Design WORKING-STORAGE for a cross-reference generator that processes COBOL source code and produces a report listing every data name and the line numbers where it is used. You need: - Input buffer for source lines - A cross-reference table (up to 500 data names, each with up to 50 line-number references) - Sorting work fields for alphabetical output - Report formatting fields - Statistics counters
Consider memory efficiency -- how much storage does your design require?
Exercise 34: Financial Calculation Engine
Design complete WORKING-STORAGE for a financial calculation engine that computes loan amortization schedules. Include: - Input parameters (principal, rate, term, start date) - Amortization schedule table (OCCURS for monthly entries with payment number, date, payment amount, principal portion, interest portion, remaining balance) - Summary fields (total interest paid, total principal paid, effective rate) - Rounding work fields (financial calculations require precise decimal handling) - Comparison fields for different loan scenarios (up to 3 scenarios side by side)
Include proper field sizes for amounts up to $10 million with cents, and rates up to 99.9999%.
Exercise 35: Comprehensive Chapter Integration
Write a complete COBOL program (IDENTIFICATION through PROCEDURE DIVISION) that demonstrates all major concepts from this chapter in a single, cohesive program. The program should:
- Use all level numbers (01, 05/10/15, 66, 77, 88)
- Include at least one REDEFINES for each pattern (date, record-type, validation, table init)
- Use INITIALIZE, INITIALIZE REPLACING, and INITIALIZE ALL TO VALUE
- Use 88-levels with single values, multiple values, and THRU ranges
- Use SET with 88-levels
- Use EVALUATE TRUE with 88-levels
- Include a FILLER-based formatted display line
- Follow all naming conventions and organizational best practices
- Be a working program that compiles and produces meaningful output
The theme should be processing a collection of employee records with different department codes, calculating department totals, and producing a formatted summary report.
Submission Guidelines
For each exercise:
1. Write your COBOL code in proper fixed-format column alignment
2. Include comments explaining your design decisions
3. For definition-only exercises, you do not need a complete program -- just the WORKING-STORAGE entries
4. For exercises requiring PROCEDURE DIVISION code, include enough context to compile and run
5. Test your code with GnuCOBOL: cobc -x your-program.cob && ./your-program