Chapter 6 Exercises: Arithmetic Operations and Numeric Processing
Tier 1: Remembering and Understanding (Exercises 1.1-1.8)
These exercises test your recall of syntax and basic understanding of arithmetic verbs.
Exercise 1.1: Identify the Verb Forms
For each of the following COBOL statements, identify (a) which arithmetic verb is used, (b) which form (TO/FROM/BY/GIVING/CORRESPONDING), and (c) which field will contain the result.
a) ADD WS-TAX TO WS-TOTAL
b) SUBTRACT WS-DISCOUNT FROM WS-PRICE GIVING WS-NET
c) MULTIPLY WS-RATE BY WS-AMOUNT
d) DIVIDE WS-TOTAL BY 12 GIVING WS-MONTHLY
e) ADD CORRESPONDING WS-MONTH TO WS-YEAR
f) DIVIDE WS-HOURS INTO WS-TOTAL-PAY
g) COMPUTE WS-AREA = WS-LENGTH * WS-WIDTH
Exercise 1.2: Translate to COBOL
Write COBOL statements for each of the following operations. Use the most appropriate verb form.
a) Add 100 to WS-BALANCE b) Subtract WS-FEE from WS-ACCOUNT, storing the result in WS-NET-BALANCE (preserve both operands) c) Multiply WS-HOURS by WS-RATE, storing in WS-GROSS-PAY d) Divide WS-ANNUAL-SALARY by 12, storing in WS-MONTHLY-PAY (use rounding) e) Calculate: WS-TOTAL = WS-PRICE * WS-QTY * (1 + WS-TAX-RATE)
Exercise 1.3: Basic Calculator
Write the DATA DIVISION entries and PROCEDURE DIVISION statements to: 1. Define two numeric fields: WS-NUM-1 (PIC 9(5)V99) and WS-NUM-2 (PIC 9(5)V99) 2. Define result fields for sum, difference, product, and quotient 3. Perform all four basic operations on 245.50 and 123.75 4. Display each result
Exercise 1.4: Precedence Prediction
Without running the code, predict the result of each COMPUTE statement. Then verify by running.
a) COMPUTE WS-R = 10 + 5 * 2
b) COMPUTE WS-R = (10 + 5) * 2
c) COMPUTE WS-R = 100 / 10 / 2
d) COMPUTE WS-R = 2 ** 3 + 1
e) COMPUTE WS-R = 2 ** (3 + 1)
f) COMPUTE WS-R = 100 - 50 + 25
g) COMPUTE WS-R = 3 + 4 * 2 ** 2
Exercise 1.5: Running Total
Write a program that: 1. Defines five numeric values: 15.75, 23.50, 8.25, 42.00, 31.10 2. Uses ADD ... TO to accumulate a running total 3. Displays the running total after each addition 4. Displays the final total
Exercise 1.6: True or False
Answer each question with True or False, and briefly explain your reasoning.
a) In ADD A TO B, the value of A is modified.
b) The GIVING phrase preserves the original operands.
c) DIVIDE 5 INTO 100 computes 5 / 100.
d) Without ROUNDED, COBOL rounds arithmetic results to the nearest value.
e) ON SIZE ERROR catches division by zero.
f) COMP-3 is recommended for financial calculations.
g) COMPUTE WS-R = 2 + 3 * 4 produces 20.
Exercise 1.7: Matching Exercise
Match each COBOL statement on the left with its mathematical equivalent on the right.
| COBOL Statement | Mathematical Equivalent |
|---|---|
1. ADD A B GIVING C |
a. C = B - A |
2. SUBTRACT A FROM B GIVING C |
b. C = A * B |
3. MULTIPLY A BY B GIVING C |
c. B = B + A |
4. DIVIDE A INTO B GIVING C |
d. C = A + B |
5. DIVIDE A BY B GIVING C |
e. C = A / B |
6. ADD A TO B |
f. C = B / A |
Exercise 1.8: Error Identification
Find the error(s) in each of the following COBOL statements:
a) ADD A + B GIVING C
b) SUBTRACT A TO B
c) MULTIPLY A INTO B
d) DIVIDE A FROM B GIVING C
e) COMPUTE WS-RESULT = WS-A +* WS-B
f) ADD CORRESPONDING A TO B GIVING C
Tier 2: Applying (Exercises 2.1-2.8)
These exercises require you to apply arithmetic verbs to practical scenarios.
Exercise 2.1: Sales Commission Calculator
Write a program that calculates sales commissions with the following rules: - Sales up to $10,000: 5% commission - Sales from $10,001 to $25,000: 5% on first $10,000 + 8% on remainder - Sales over $25,000: 5% on first $10,000 + 8% on next $15,000 + 12% on remainder
Test with sales amounts of $8,000, $18,000, and $50,000. Use COMP-3 fields and ROUNDED.
Exercise 2.2: Invoice Calculator
Write a program to calculate an invoice with three line items: - Widget A: 10 units at $24.95 each - Widget B: 5 units at $49.99 each - Widget C: 25 units at $9.50 each
Calculate: 1. Each line item total (quantity * price) 2. Subtotal (sum of all line items) 3. Sales tax at 8.25% 4. Grand total
Display a formatted invoice with all amounts.
Exercise 2.3: Paycheck Calculator
Write a program that calculates a weekly paycheck: - Regular hours (up to 40): $22.50/hour - Overtime hours (over 40): 1.5 times regular rate - Federal tax: 22% of gross - State tax: 5.75% of gross - Social Security: 6.2% of gross (up to annual limit of $160,200) - Medicare: 1.45% of gross
Input: Employee worked 47 hours this week. Calculate gross pay, each deduction, and net pay.
Exercise 2.4: Temperature Conversion Table
Write a program that produces a temperature conversion table from Fahrenheit to Celsius for the following values: -40, -20, 0, 32, 50, 72, 98.6, 100, 150, 212.
Formula: C = (F - 32) * 5 / 9
Use COMPUTE with ROUNDED. Display results in a formatted table.
Exercise 2.5: ADD CORRESPONDING Practice
Define two group items:
01 WS-QUARTERLY-SALES.
05 WS-PRODUCT-A PIC 9(7)V99 VALUE 15000.00.
05 WS-PRODUCT-B PIC 9(7)V99 VALUE 22500.00.
05 WS-PRODUCT-C PIC 9(7)V99 VALUE 8750.00.
05 WS-PRODUCT-D PIC 9(7)V99 VALUE 31200.00.
01 WS-YEARLY-SALES.
05 WS-PRODUCT-A PIC 9(9)V99 VALUE ZERO.
05 WS-PRODUCT-B PIC 9(9)V99 VALUE ZERO.
05 WS-PRODUCT-C PIC 9(9)V99 VALUE ZERO.
05 WS-PRODUCT-D PIC 9(9)V99 VALUE ZERO.
Write a program that: 1. Adds the quarterly figures to yearly totals four times (simulating four quarters) 2. Displays the yearly total for each product 3. Calculates and displays the grand total of all products
Exercise 2.6: DIVIDE with REMAINDER
Write a program that: 1. Takes a total of 1,000 items and distributes them across 7 warehouses 2. Uses DIVIDE with REMAINDER to find how many each warehouse gets and how many are left over 3. Distributes the remainder one at a time to warehouses (warehouse 1 gets one extra, warehouse 2 gets one extra, etc.) 4. Displays the final allocation for each warehouse
Exercise 2.7: Percentage Calculator
Write a program that computes: 1. What percentage is 35 of 200? (formula: part / whole * 100) 2. What is 17.5% of $3,450.00? 3. If a price increased from $89.99 to $104.99, what is the percentage increase? 4. If an item was $150.00 and is now 30% off, what is the sale price?
Exercise 2.8: Time Conversion
Write a program that converts 10,000 seconds into hours, minutes, and seconds using DIVIDE with REMAINDER.
Expected output: 2 hours, 46 minutes, 40 seconds.
Tier 3: Analyzing (Exercises 3.1-3.5)
These exercises require analysis of arithmetic behavior and precision issues.
Exercise 3.1: Simple Interest with Validation
Write a complete simple interest calculator (I = P * R * T) that: 1. Uses COMP-3 fields for all monetary values 2. Validates that principal is positive 3. Validates that rate is between 0 and 1 (0% to 100%) 4. Validates that time is positive 5. Uses ON SIZE ERROR for all calculations 6. Calculates both the interest and the total (principal + interest) 7. Tests with: $5,000 at 3.5% for 5 years
Exercise 3.2: Truncation vs Rounding Analysis
Write a program that demonstrates the difference between truncation and rounding by: 1. Computing 1/3, 1/6, 1/7, 2/3, 5/6, and 6/7 with both truncation and rounding 2. Storing results in PIC 9(3)V99 fields 3. Displaying a comparison table 4. For each, multiplying the truncated and rounded results by the original divisor 5. Showing which result (truncated or rounded) is closer to the original dividend
Exercise 3.3: Compound Interest Comparison
Write a program that compares compound interest results for: - Principal: $10,000 - Rate: 6.5% - Time: 10 years - Compounding: Annual, Quarterly, Monthly, Daily (365), Continuous (use e^(r*t) approximation)
Display the future value and interest earned for each compounding frequency. Analyze which produces the most interest and by how much.
Exercise 3.4: Precision Loss Investigation
Write a program that demonstrates precision loss by: 1. Starting with exactly $1,000,000.00 2. Dividing by 7, then multiplying by 7 (should get back to $1,000,000.00) 3. Doing this with: a. PIC 9(7)V99 DISPLAY fields b. PIC 9(7)V99 COMP-3 fields c. PIC 9(7)V9(6) fields (more decimal places) 4. Repeating the divide/multiply cycle 10 times 5. Showing the accumulated error after each cycle
Exercise 3.5: Operator Precedence Deep Dive
For each expression below: 1. Write the evaluation order step by step 2. Predict the result 3. Write a COBOL COMPUTE statement 4. Add parentheses to change the evaluation order and get a different result
a) 2 + 3 * 4 ** 2 - 10 / 5
b) 100 / 4 / 5 * 2
c) 2 ** 2 ** 3
d) 50 - 10 - 5 + 3 * 2
Tier 4: Evaluating and Creating (Exercises 4.1-4.5)
These exercises require you to design and implement complete solutions.
Exercise 4.1: Progressive Tax Calculator
Write a complete progressive tax calculator using the following simplified 2024 US tax brackets for single filers:
| Bracket | Rate |
|---|---|
| $0 - $11,000 | 10% |
| $11,001 - $44,725 | 12% |
| $44,726 - $95,375 | 22% |
| $95,376 - $182,100 | 24% |
| $182,101 - $231,250 | 32% |
| $231,251 - $578,125 | 35% |
| Over $578,125 | 37% |
Requirements: 1. Accept a gross income (hardcoded for testing) 2. Apply standard deduction of $13,850 3. Calculate tax for each bracket 4. Display a breakdown showing tax in each bracket 5. Calculate and display the effective tax rate 6. Test with incomes of $35,000, $75,000, $150,000, and $500,000 7. Use COMP-3 for all monetary fields 8. Use ON SIZE ERROR on all calculations
Exercise 4.2: Loan Payment Calculator
Write a program that: 1. Calculates the monthly payment for a loan 2. Generates an amortization schedule showing the first 12 months 3. For each payment, shows: payment number, payment amount, interest portion, principal portion, remaining balance 4. Shows year-end totals for interest and principal paid 5. Test with: $150,000 loan, 6% annual rate, 15-year term
Exercise 4.3: Currency Conversion Engine
Write a program that: 1. Defines an exchange rate table with at least 5 currencies (EUR, GBP, JPY, CAD, CHF) 2. Converts a USD amount to each currency 3. Converts each result back to USD 4. Shows the round-trip conversion accuracy (original vs. converted-back amount) 5. Calculates the total conversion error across all currencies 6. All calculations must use COMP-3 and ROUNDED
Exercise 4.4: Rounding Method Comparison
Write a program that: 1. Processes 100 randomly seeded transaction amounts between $0.00 and $99.99 2. For each transaction, calculates tax at 8.75% 3. Applies three rounding methods: truncation, half-up rounding, and (if your compiler supports it) banker's rounding 4. Accumulates totals for each method 5. Compares the totals to a "true" total calculated with high-precision fields 6. Displays which method produces the least accumulated error
(Note: If your compiler does not support ROUNDED MODE, simulate banker's rounding by checking if the discarded digit is exactly 5 and the preceding digit is even.)
Exercise 4.5: Financial Statement Calculator
Write a program that computes the following financial metrics from these sample figures:
Revenue: $1,250,000.00
Cost of Goods: $ 750,000.00
Operating Expenses:$ 275,000.00
Interest Expense: $ 45,000.00
Tax Rate: 21%
Calculate and display: 1. Gross Profit (Revenue - COGS) 2. Gross Margin % (Gross Profit / Revenue * 100) 3. Operating Income (Gross Profit - Operating Expenses) 4. Operating Margin % (Operating Income / Revenue * 100) 5. Income Before Tax (Operating Income - Interest) 6. Income Tax 7. Net Income 8. Net Profit Margin % (Net Income / Revenue * 100)
Tier 5: Advanced Challenges (Exercises 5.1-5.4)
These exercises push the boundaries of COBOL arithmetic.
Exercise 5.1: Full Amortization Schedule with Analysis
Extend Exercise 4.2 to produce a complete amortization schedule for a 30-year mortgage ($250,000 at 6.5%). Requirements:
- Show monthly detail for the first and last year
- Show yearly summaries for all 30 years
- Calculate the "crossover point"---the month where principal exceeds interest in the payment
- Show cumulative totals at 5-year intervals
- Handle the last payment adjustment (when balance is less than the regular payment)
- Verify that the sum of all principal payments equals the original loan amount
- All calculations use COMP-3 with ROUNDED and ON SIZE ERROR
Exercise 5.2: Multi-State Payroll Engine
Design and implement a payroll calculation engine that handles: 1. Three employees with different hourly rates and hours worked 2. Federal income tax (use the progressive brackets from Exercise 4.1, annualized) 3. State income tax for three different states: - State A: Flat 5% - State B: Progressive (3% up to $30,000, 5% up to $60,000, 7% above) - State C: No income tax 4. Social Security (6.2% up to $160,200 annually) with year-to-date tracking 5. Medicare (1.45%, plus 0.9% additional above $200,000 annually) 6. Overtime at 1.5x for hours over 40 7. Year-to-date accumulators for all categories 8. Display a formatted pay stub for each employee
Exercise 5.3: Investment Growth Comparison
Write a program that compares three investment scenarios over 30 years:
- Savings Account: $10,000 initial deposit, 2% annual interest, compounded monthly
- Certificate of Deposit: $10,000 initial, 4.5% annual, compounded quarterly, 5-year terms (renewed automatically)
- Investment Portfolio: $10,000 initial with $200 monthly contribution, 8% average annual return, compounded monthly
Display a year-by-year comparison showing the balance of each investment. Calculate the total contributions and total growth for each option.
Exercise 5.4: The Penny Problem
Write a program that demonstrates the "penny problem" (related to the case study):
- Start with exactly $10,000,000.00 (ten million dollars)
- Process 1,000,000 transactions, each dividing an account balance by 3 and multiplying back by 3
- Track the cumulative error using three approaches: a. DISPLAY fields (PIC 9(9)V99) b. COMP-3 fields (PIC S9(9)V99) c. COMP-3 fields with extra precision (PIC S9(9)V9(6))
- After all transactions, display the balance for each approach and the difference from $10,000,000.00
- Discuss the implications for a real banking system
How to Submit
For each exercise: 1. Write complete, compilable COBOL programs 2. Include appropriate comments explaining your approach 3. Use proper fixed-format column alignment 4. Test your programs with the specified test data 5. Verify results manually for at least one test case
Solutions to selected exercises are provided in code/exercise-solutions.cob.