Chapter 10 Exercises: Tables and Arrays
These exercises are organized into five tiers of increasing difficulty. Work through them sequentially to build mastery, or jump to the tier that matches your current skill level.
Tier 1: Foundation (Exercises 1-5)
These exercises cover basic table definition, accessing elements with subscripts, and simple iteration.
Exercise 1: First Table
Define a one-dimensional table of 10 integers (PIC 9(3)) in WORKING-STORAGE. Write a program that: 1. Loads the values 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 into the table using MOVE statements. 2. Uses PERFORM VARYING to display all 10 values. 3. Calculates and displays the sum of all elements.
Hint: Use a subscript variable (PIC 99) for iteration.
Exercise 2: Table Initialization
Define a table of 5 employee names (PIC X(25)) using the REDEFINES technique. The names should be: - "SMITH, JOHN" - "MARTINEZ, MARIA" - "CHEN, DAVID" - "WILLIAMS, SARAH" - "PATEL, ANITA"
Write a program that displays all names with their position numbers (1 through 5).
Exercise 3: Subscript Validation
Write a program with a table of 12 month names. Accept a number from the user and display the corresponding month name. If the number is less than 1 or greater than 12, display an error message instead. Test with valid and invalid inputs.
Exercise 4: Table Maximum and Minimum
Define a table of 8 numeric values (PIC 9(5)). Load these values: 42500, 18300, 67200, 31000, 95400, 12800, 55600, 78900. Write a program that finds and displays: 1. The maximum value and its position 2. The minimum value and its position
Exercise 5: Day-of-Week Lookup
Create a lookup table mapping day numbers (1-7) to day names (Sunday through Saturday). Accept a day number from the user, validate it, and display the corresponding day name. Allow repeated lookups until the user enters 0.
Solution: See code/exercise-solutions.cob, section 0500-EXERCISE-05.
Tier 2: Skill Building (Exercises 6-10)
These exercises introduce loading tables from computed values, using tables as accumulators, and working with structured table entries.
Exercise 6: Multiplication Table
Build a one-dimensional table of 12 entries where each entry contains the product of its position and a number entered by the user. For example, if the user enters 7, the table should contain 7, 14, 21, 28, ..., 84. Display the table in a formatted manner:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 12 = 84
Exercise 7: Grade Frequency Counter
Define a table of 5 counters, one for each letter grade (A, B, C, D, F). Accept 20 letter grades from the user (or hardcode them). Use the table to count how many of each grade were entered. Display the frequency of each grade at the end.
Hint: Map 'A' to position 1, 'B' to position 2, etc., using EVALUATE or IF statements.
Exercise 8: Temperature Conversion Table
Build a table that holds Celsius values from 0 to 100 in increments of 10, along with their Fahrenheit equivalents. Calculate the Fahrenheit values using the formula F = (C * 9 / 5) + 32. Display the complete conversion table.
Solution: See code/exercise-solutions.cob, section 0800-EXERCISE-08.
Exercise 9: Employee Salary Lookup
Define a table of 10 employees, each with an employee ID (PIC 9(5)), name (PIC X(20)), and salary (PIC 9(7)V99). Load sample data using MOVE statements. Write a program that: 1. Displays all employees in a formatted table. 2. Accepts an employee ID from the user. 3. Searches the table sequentially (without SEARCH) using PERFORM VARYING. 4. Displays the employee's name and salary if found, or "Not found" if not.
Exercise 10: Accumulator Table -- Category Sales
Define a table of 5 categories (Electronics, Clothing, Food, Hardware, Books) and a parallel accumulator table of 5 totals. Process 15 transactions (hardcoded: category number 1-5, amount). Accumulate each amount into the appropriate category total. Display a summary showing category names and their totals.
Tier 3: Intermediate (Exercises 11-17)
These exercises introduce multi-dimensional tables, the SEARCH statement, and INDEXED BY.
Exercise 11: Two-Dimensional Seating Chart
Define a 5 x 8 table representing rows and seats in a small theater. Each cell contains a status flag: 'O' for open, 'X' for occupied. Initialize all seats to 'O'. Then mark several seats as occupied. Display the seating chart as a grid:
Seat: 1 2 3 4 5 6 7 8
Row 1: O O X O O X O O
Row 2: O X X O O O O O
...
Count and display the total number of open and occupied seats.
Exercise 12: Student Grades Matrix
Define a 2D table: 5 students x 4 exams. Load grade data (scores 0-100). Calculate and display: 1. Each student's average across all 4 exams 2. Each exam's average across all 5 students 3. The overall class average
Display the data in a formatted grid with row and column headers.
Solution: See code/exercise-solutions.cob, section 1200-EXERCISE-12.
Exercise 13: SEARCH with INDEXED BY
Create a table of 15 product entries, each with a product code (PIC X(6)), description (PIC X(20)), and unit price (PIC 9(5)V99). Use INDEXED BY on the table. Write a program that: 1. Accepts a product code from the user. 2. Uses the SEARCH statement to find the product. 3. Displays the description and price if found. 4. Displays "Product not found" if not found. 5. Loops until the user enters "QUIT".
Remember to SET the index to 1 before each SEARCH.
Exercise 14: Multiple WHEN Clauses
Using the product table from Exercise 13, write a SEARCH that finds products in one of two price ranges: - WHEN unit price < 10.00 -- display as "Budget item" - WHEN unit price >= 100.00 -- display as "Premium item"
Use multiple WHEN clauses in a single SEARCH statement.
Exercise 15: Three-Dimensional Table
Define a 3D table: 3 warehouses x 4 product categories x 12 months, storing quantity-on-hand (PIC 9(6)). Load sample data for at least 2 warehouses, 2 categories, and 3 months. Write a program that displays: 1. A detailed breakdown for each warehouse 2. Category totals across all warehouses 3. Monthly totals across all categories and warehouses
Exercise 16: SEARCH ALL Binary Search
Create a sorted table of 8 error codes (ascending by code) with corresponding error messages. Use SEARCH ALL to look up an error code entered by the user. Display the error message if found, or list all valid codes if not found.
Solution: See code/exercise-solutions.cob, section 1600-EXERCISE-16.
Exercise 17: Parallel Tables with SEARCH VARYING
Define two parallel tables of the same size: - Table 1: Country codes (PIC X(2)), sorted - Table 2: Country names (PIC X(20))
Use SEARCH with the VARYING clause to search Table 1 by country code and retrieve the corresponding country name from Table 2. Handle the case where the code is not found.
Tier 4: Advanced (Exercises 18-27)
These exercises combine multiple table techniques and introduce OCCURS DEPENDING ON.
Exercise 18: SEARCH ALL with Compound Keys
Define a table of 20 entries with two key fields: department code (PIC X(4)) and employee ID (PIC 9(5)), plus employee name (PIC X(20)). Define the table with compound ascending keys. Sort the data appropriately and use SEARCH ALL with both keys in the WHEN clause to find specific employees.
Exercise 19: Table Sorting (Bubble Sort)
Implement a bubble sort algorithm for a one-dimensional table of 15 numeric values. Load the table with unsorted values, display the table before sorting, perform the sort, and display the table after sorting. Count and display the number of swaps performed.
Exercise 20: Three-Dimensional Sales Report
Define a 3D table: 3 salespersons x 4 products x 12 months. Load sample data for at least Q1 (months 1-3). Generate a formatted report showing: 1. Quarterly totals by salesperson and product 2. Salesperson total across all products 3. Grand total across all salespersons
Solution: See code/exercise-solutions.cob, section 2000-EXERCISE-20.
Exercise 21: Descending Key SEARCH ALL
Create a table of student test scores sorted in descending order, with the highest score first. Each entry has a score (PIC 9(4)) and student name (PIC X(20)). Use DESCENDING KEY IS and SEARCH ALL to find a student by their exact score.
Exercise 22: OCCURS DEPENDING ON -- Shopping Cart
Implement a shopping cart using OCCURS DEPENDING ON (1 TO 20 items). Write routines to: 1. Add an item (product code, quantity, price) to the cart 2. Remove an item by position (shift subsequent items up) 3. Display all items with line totals and a cart total 4. Display the current item count and cart capacity
Exercise 23: Variable-Length Record Processing
Design a variable-length record structure for an invoice: - Fixed header: invoice number, date, customer ID (30 bytes) - Variable: 1 to 25 line items, each with product code, description, quantity, and price
Write a program that builds three invoices with different numbers of line items (3, 7, and 15). Display each invoice with its line items and total, and show the record length for each.
Exercise 24: Dynamic Inventory List (ODO)
Create a variable-length inventory table using OCCURS DEPENDING ON (1 TO 100 items). Implement operations to: 1. Add items to the inventory 2. Remove an item by part number (search, then shift) 3. Display the current inventory 4. Show the count of active items
Solution: See code/exercise-solutions.cob, section 2400-EXERCISE-24.
Exercise 25: Table-Driven Validation
Create a validation table containing field rules: field name, minimum length, maximum length, required flag, and allowed character types (A=alpha, N=numeric, X=alphanumeric). Write a program that validates 5 input fields against the table rules and reports all validation errors.
Exercise 26: Rate Table Interpolation
Define a shipping rate table with distance ranges and weight ranges: - Distances: 0-100 mi, 101-500 mi, 501-1000 mi, 1001+ mi - Weights: 0-1 lb, 1-5 lb, 5-20 lb, 20-50 lb, 50+ lb
This creates a 2D rate table. Write a program that accepts a distance and weight, finds the appropriate cell, and displays the shipping cost. Handle edge cases where values fall exactly on boundaries.
Exercise 27: Multi-Dimensional Report with Cross-Tabs
Define a 3D table: 4 regions x 3 product lines x 4 quarters. Load the table with sales data. Generate a cross-tabulation report that displays: 1. Each region as a separate section 2. Products as rows, quarters as columns 3. Row totals (product annual totals) 4. Column totals (quarterly totals per region) 5. A summary section showing region totals side by side
Tier 5: Mastery (Exercises 28-35)
These exercises represent production-level challenges combining all table concepts.
Exercise 28: Complete Payroll System
Build a payroll calculation program using multiple interrelated tables: - Federal tax bracket table (7 brackets with progressive rates) - State tax rate table (10 states, mix of flat and graduated) - Deduction code table (insurance, 401k, etc.) - Employee table loaded with 10 employees
Calculate gross pay, federal tax, state tax, deductions, and net pay for each employee. Display individual pay stubs and a company-wide summary report.
Exercise 29: Matrix Operations
Implement basic matrix operations using 2D tables: 1. Matrix addition: C = A + B (both 4x4) 2. Matrix transposition: B = A^T 3. Matrix multiplication: C = A * B (A is 3x4, B is 4x2, C is 3x2)
Display the input matrices and results in formatted grid layout.
Exercise 30: Hash Table Simulation
Implement a simple hash table using a fixed-size COBOL table of 53 entries. Use a hash function (sum of character values MOD 53) to determine the position. Handle collisions using linear probing. Implement: 1. INSERT: Add a key-value pair 2. LOOKUP: Find a value by key 3. DELETE: Remove an entry by key 4. DISPLAY: Show the entire hash table with occupied/empty markers
Exercise 31: Multi-Level Control Break Report
Process a table of 50 transaction records (loaded via MOVE statements), each with department, section, employee ID, and amount. The data is pre-sorted by department and section. Generate a report with: - Detail lines for each transaction - Section subtotals - Department subtotals - Grand total - Use accumulator tables for each level of subtotals.
Exercise 32: Dynamic Table Merge
Given two sorted tables (Table A: 15 entries, Table B: 20 entries), merge them into a single sorted output table (35 entries) using the classic merge algorithm. Each entry has a key field and a data field. Handle duplicate keys by keeping both entries. Display all three tables.
Exercise 33: Sparse Matrix Representation
Implement a sparse matrix (mostly zeros) using a table of non-zero entries, each containing row, column, and value. Support: 1. Setting a value at (row, col) 2. Getting a value at (row, col) -- return 0 if not stored 3. Displaying the full matrix (filling in zeros for unset positions) 4. Adding two sparse matrices
Use OCCURS DEPENDING ON to size the non-zero entry table dynamically.
Exercise 34: Configuration-Driven Processing
Create a processing rules table where each entry defines: rule ID, field to check, comparison operator (EQ, NE, GT, LT, GE, LE), comparison value, and action code. Write a "rule engine" that reads a data record and applies each rule in the table, collecting the action codes for all matching rules. Display which rules fired and what actions would be taken.
Exercise 35: Inventory Management System
Build a complete inventory management system using: - A product table (OCCURS DEPENDING ON, up to 500 products) with product ID, description, category, reorder point, and current quantity - A warehouse table (3 warehouses, each with their own quantity for each product) using a 2D structure - A transaction log table (variable length) recording all stock movements
Implement: 1. Add new product 2. Receive stock (increase quantity at a specific warehouse) 3. Ship stock (decrease quantity, check availability) 4. Transfer between warehouses 5. Low stock report (products below reorder point at any warehouse) 6. Inventory valuation report (quantity * unit cost, by warehouse) 7. Transaction history display
General Guidelines
- All programs should compile and run without errors.
- Use proper COBOL fixed-format column alignment (columns 7-72).
- Include IDENTIFICATION DIVISION, DATA DIVISION, and PROCEDURE DIVISION in every program.
- Use meaningful data names following the WS- prefix convention for WORKING-STORAGE items.
- Include appropriate error handling for subscript bounds.
- For exercises requiring user input, include validation.
- For display output, use formatted fields (PIC with Z suppression, $, decimal points) where appropriate.
- Test your programs with both normal and boundary cases.