Chapter 7 Exercises: Conditional Logic
These exercises progress from basic concept reinforcement through advanced business logic implementation. Work through them in order; each tier builds on the skills developed in previous tiers.
Tier 1: Fundamentals (Exercises 1-7)
Exercise 1: Voting Eligibility
Write a COBOL program that checks whether a person is eligible to vote. The person must meet ALL of the following criteria: - Age is 18 or older - Is a citizen (flag = "Y") - Is registered (flag = "Y")
Display a message indicating eligibility. If not eligible, display which specific criteria were not met.
Exercise 2: Simple Grade Calculator
Write an IF/ELSE chain that assigns a letter grade based on a numeric score: - 90-100: A - 80-89: B - 70-79: C - 60-69: D - Below 60: F
Display both the score and the letter grade. Use only IF/ELSE/END-IF (no EVALUATE).
Exercise 3: Shipping Rate Calculator
Given package weight (in pounds), shipping distance (in miles), and an expedited flag (Y/N), calculate the shipping rate using these compound conditions:
| Condition | Rate Formula |
|---|---|
| Expedited AND weight > 50 lbs | $25.00 + ($0.75 x weight) + ($0.10 x distance) |
| Expedited AND weight <= 50 lbs | $15.00 + ($0.50 x weight) + ($0.08 x distance) |
| Standard AND weight > 50 AND distance > 1000 | $20.00 + ($0.40 x weight) + ($0.05 x distance) |
| Standard AND weight > 50 | $15.00 + ($0.30 x weight) |
| Standard AND distance > 1000 | $10.00 + ($0.25 x weight) + ($0.03 x distance) |
| Standard (all others) | $5.00 + ($0.20 x weight) |
Exercise 4: Leap Year Checker
Write a program that determines if a year is a leap year using these rules: - Divisible by 4: leap year - Except if divisible by 100: not a leap year - Except if divisible by 400: leap year
Test with years: 2000, 1900, 2024, 2023. Display the result for each.
Hint: Use the FUNCTION MOD intrinsic function or compute the remainder.
Exercise 5: Student Classification
Define 88-level condition names for student classification based on completed credits: - Freshman: 0-29 credits - Sophomore: 30-59 credits - Junior: 60-89 credits - Senior: 90-119 credits - Graduate: 120+ credits
Write code that accepts a credit count, uses EVALUATE TRUE with the condition names to set the classification, and displays the result.
Exercise 6: Sign Condition Practice
Given three numeric variables representing monthly profit/loss for January, February, and March, write code that: 1. Tests each month using POSITIVE, NEGATIVE, and ZERO sign conditions 2. Counts the number of profitable, loss, and break-even months 3. Determines the overall quarterly trend (positive if more profit months, negative if more loss months, neutral if equal)
Exercise 7: Class Condition Validation
Write a program that validates the following input fields using class conditions: - Employee name: must be ALPHABETIC - Employee ID: must be NUMERIC - Department code: must be ALPHABETIC-UPPER
Display VALID or INVALID for each field. Test with both valid and invalid data.
Tier 2: Applied Concepts (Exercises 8-14)
Exercise 8: Tax Bracket Calculator
Using EVALUATE TRUE, implement a simplified federal income tax calculator for single filers:
| Taxable Income | Tax Rate | Base Tax |
|---|---|---|
| $0 - $11,000 | 10% | $0 |
| $11,001 - $44,725 | 12% | $1,100 |
| $44,726 - $95,375 | 22% | $5,147 |
| $95,376 - $182,100 | 24% | $16,290 |
| $182,101 - $231,250 | 32% | $37,104 |
| Over $231,250 | 35% | $52,832 |
Calculate: Base Tax + (Income - Lower Bracket Bound) x Rate. Display the bracket, rate, and total tax.
Exercise 9: Day of Week EVALUATE
Write a program that uses EVALUATE to determine: 1. The name of the day (1=Monday through 7=Sunday) 2. Whether it is a weekday or weekend 3. The business hours message ("Regular hours", "Early closing", "Closed")
Use EVALUATE with ALSO to combine day-of-week with time-of-day for the business hours determination.
Exercise 10: Convert Nested IF to EVALUATE
The following nested IF structure determines an employee bonus percentage. Convert it to an EVALUATE TRUE ALSO TRUE:
IF employee is full-time THEN
IF years >= 10 THEN bonus = 10%
ELSE IF years >= 5 THEN bonus = 7.5%
ELSE IF years >= 1 THEN bonus = 5%
ELSE bonus = 2%
ELSE IF employee is part-time THEN
IF years >= 5 THEN bonus = 5%
ELSE bonus = 2.5%
ELSE IF employee is temporary THEN
bonus = 0%
Write both the nested IF version and the EVALUATE version. Display the results from both to verify they match.
Exercise 11: Password Strength Checker
Write a program that evaluates password strength based on multiple criteria. Define appropriate condition names for the results. Check for: - Length (at least 8 characters) -- count non-space characters - Contains at least one uppercase letter (check each character) - Contains at least one digit (check each character)
Rate the password as: - STRONG: all three criteria met - MEDIUM: two criteria met - WEAK: one or zero criteria met
Exercise 12: Time Zone Converter
Given a time in 24-hour format (hours: 0-23) and a source time zone code (EST, CST, MST, PST), convert to all four US time zones. Use EVALUATE for the zone offset and IF for handling day boundary crossing (when hours go below 0 or above 23).
Exercise 13: BMI Calculator and Classification
Write a program that: 1. Accepts weight (in pounds) and height (in inches) 2. Calculates BMI = (weight / (height * height)) * 703 3. Uses EVALUATE TRUE with THRU ranges to classify: - Under 18.5: Underweight - 18.5 - 24.9: Normal - 25.0 - 29.9: Overweight - 30.0 and above: Obese 4. Displays the BMI value and classification
Define 88-level conditions for each BMI category.
Exercise 14: Input Validation Engine
Build a validation engine that checks: 1. Social Security Number format (NNN-NN-NNNN) using a user-defined class 2. Email address (must contain exactly one @ character) 3. Phone number format (NNN-NNN-NNNN) using a user-defined class 4. ZIP code (must be NUMERIC and exactly 5 digits)
Collect all errors (do not stop at the first one) and display a validation report showing which fields passed and which failed.
Tier 3: Intermediate Challenges (Exercises 15-21)
Exercise 15: Multi-Tier Pricing Engine
Implement a pricing engine where the discount depends on THREE factors simultaneously: - Customer tier (Gold, Silver, Bronze) - Order quantity (1-10, 11-50, 51-100, 100+) - Product category (Electronics, Clothing, Food)
Create a 3-dimensional discount matrix using EVALUATE with two ALSO clauses. Display the base price, discount percentage, and final price.
Exercise 16: Insurance Premium Calculator
Calculate an auto insurance premium based on: - Driver age (under 25: high risk, 25-65: standard, over 65: moderate risk) - Driving record (0 accidents: clean, 1-2: minor, 3+: major) - Vehicle type (sedan, SUV, sports car) - Coverage level (basic, standard, premium)
Use a combination of EVALUATE and condition names. The base premium should be multiplied by risk factors from each category.
Exercise 17: EVALUATE State Machine
Implement an order processing state machine with these states: NEW, CONFIRMED, PROCESSING, SHIPPED, DELIVERED, CANCELLED, RETURNED.
Define valid transitions (e.g., NEW can become CONFIRMED or CANCELLED, but not SHIPPED). Use EVALUATE TRUE ALSO TRUE where one axis is the current state and the other is the requested transition event. Display whether each transition is valid or invalid.
Exercise 18: De Morgan's Law Practice
For each of the following conditions, write the De Morgan's equivalent and verify both produce the same result with test data:
NOT (TEMP > 100 AND HUMIDITY > 80)NOT (STATUS = "A" OR STATUS = "P")NOT (AGE >= 18 AND AGE <= 65 AND CITIZEN = "Y")NOT ((BALANCE > 0 AND NOT OVERDUE) OR VIP-CUSTOMER)
Write a program that tests both forms with multiple data sets and confirms they always agree.
Exercise 19: Calendar Month Validator
Write a comprehensive date validator that checks: 1. Month is 1-12 2. Day is valid for the given month (including February in leap years) 3. Year is in a reasonable range (1900-2099)
Use EVALUATE for the month-to-max-day mapping and IF for the leap year check. Define condition names for month categories (30-day months, 31-day months, February).
Exercise 20: Bank Account Transaction Processor
Implement a transaction processor with these rules: - Deposits: always allowed on active accounts - Withdrawals: allowed only if sufficient balance and account is active - Transfers: allowed if sufficient balance, active account, and destination account is also active - Account closure: allowed only if balance is zero and no pending transactions
Use condition names for account status and transaction types. Implement a processing loop that handles 5 test transactions against a single account and displays the running balance.
Exercise 21: Employee Benefits Eligibility
Write a program that determines employee benefits eligibility based on: - Employment type (Full-time, Part-time, Contract) - Years of service (0, 1-2, 3-5, 6-10, 10+) - Performance rating (A, B, C, D)
Benefits to evaluate: health insurance level, retirement plan eligibility, stock options, tuition reimbursement, and vacation days. Use EVALUATE TRUE ALSO TRUE for the main decision matrix and condition names throughout.
Tier 4: Advanced Applications (Exercises 22-30)
Exercise 22: International Shipping Zone Calculator
Implement a shipping zone and cost calculator: - Origin and destination countries grouped into regions (US, EU, APAC, Other) - Zones: A (same region), B (adjacent regions), C (distant regions), D (remote) - Base rates vary by zone; weight surcharges apply per kilogram - Customs fees apply to cross-region shipments - Hazardous material surcharge applies to specific product codes
Use EVALUATE with ALSO to determine the zone from origin/destination regions. Use nested conditions for surcharges and fees.
Exercise 23: Credit Score Simulator
Write a program that simulates credit score changes based on financial events: - On-time payment: +5 points - Late payment (30 days): -25 points - Late payment (60 days): -50 points - New credit inquiry: -5 points - Account paid off: +20 points - Bankruptcy: -200 points
Start with an initial score and process a list of 10 events. After each event, re-evaluate the credit tier using condition names and display the running score and category. Ensure the score stays within the 300-850 range.
Exercise 24: Complex Boolean Expression Debugger
Write a program that evaluates a complex boolean expression step by step, showing the intermediate results. Given variables A, B, C, D (each Y or N), evaluate:
(A AND B) OR (C AND NOT D) AND (A OR C)
Display: the value of each variable, the result of each sub-expression, and the final result. Test with all 16 possible combinations of A, B, C, D.
Exercise 25: Restaurant Tip Calculator with Conditions
Write a program that calculates a restaurant tip based on: - Base service quality (Excellent, Good, Fair, Poor) - Party size (1-4, 5-8, 9+) - Special conditions: happy hour (-2%), takeout (-5%), holiday (+3%)
Use EVALUATE for the base tip percentage, then IF conditions to adjust for special circumstances. Calculate and display the tip amount and total bill.
Exercise 26: Flight Booking Validator
Implement a flight booking validator that checks: - Passenger age (infant, child, adult, senior -- different rules for each) - Seat class (Economy, Business, First) - Route type (Domestic, International) - Booking status (Confirmed, Waitlisted, Standby) - Special services (wheelchair, unaccompanied minor, pet in cabin)
Validate that all combinations are allowed (e.g., unaccompanied minor only for children aged 5-11, certain seat classes required for international). Use EVALUATE with multiple ALSO clauses.
Exercise 27: Payroll Deduction Engine
Implement a payroll deduction calculator that processes: - Federal tax (based on filing status and income brackets) - State tax (based on state code -- implement 5 different state rules) - Social Security (6.2% up to wage base limit) - Medicare (1.45%, plus 0.9% additional above threshold) - Health insurance (varies by plan: basic, standard, premium, family) - 401(k) contribution (percentage of gross, with annual limit)
Each deduction has complex eligibility and calculation rules. Display an itemized pay stub.
Exercise 28: Regex-Like Pattern Matcher
Implement a simplified pattern matching engine using COBOL conditions. Support these patterns:
- # matches any digit
- @ matches any letter
- * matches any character
- Literal characters match themselves
Write a function that takes a pattern and a string, evaluates character by character, and returns whether the string matches the pattern. Test with phone numbers, dates, and product codes.
Exercise 29: Medical Triage System
Implement an emergency room triage system that assigns priority levels (1-5) based on: - Vital signs: heart rate, blood pressure (systolic/diastolic), temperature, oxygen saturation - Chief complaint category (chest pain, trauma, respiratory, neurological, other) - Patient age (pediatric, adult, geriatric) - Consciousness level (alert, verbal response, pain response, unresponsive)
Use condition names extensively for vital sign ranges and complaint categories. Implement the decision tree using EVALUATE TRUE ALSO TRUE.
Exercise 30: Complete Validation Framework
Design and implement a reusable validation framework that: 1. Defines a validation rule table with fields for: rule ID, field name, validation type (REQUIRED, NUMERIC, ALPHA, RANGE, PATTERN, CUSTOM), and parameters 2. Processes each rule against input data 3. Collects all validation errors with field name, rule ID, and error message 4. Generates a formatted validation report
Implement at least 8 different validation types. Test with a customer registration form containing 6 or more fields.
Tier 5: Integration and Design (Exercises 31-38)
Exercise 31: Rule Engine with External Configuration
Design a business rule engine where rules are defined in a WORKING-STORAGE table rather than hard-coded in the PROCEDURE DIVISION. Each rule has: - Rule ID - Field to check - Operator (EQ, NE, GT, LT, GE, LE, RANGE, IN-LIST) - Comparison value(s) - Action code (APPROVE, DENY, REFER, FLAG)
Write code that iterates through the rule table, evaluates each rule dynamically, and produces a decision. This mimics how production COBOL systems implement configurable business rules.
Exercise 32: Multi-Currency Transaction Processor
Build a transaction processor that handles multiple currencies: - Support 5 currencies with exchange rates - Validate that the currency is supported - Convert transaction amount to base currency - Apply different fee structures per currency pair - Check daily transaction limits per currency - Flag suspicious cross-currency patterns
Use EVALUATE with ALSO for the fee structure matrix and condition names for currency validation.
Exercise 33: Inventory Reorder System
Implement an inventory management system that determines reorder actions: - Current stock level vs. minimum stock level - Demand forecast (trending up, stable, trending down) - Supplier lead time (short, medium, long) - Budget availability - Seasonal adjustments
Use EVALUATE TRUE ALSO TRUE for the reorder decision matrix. Calculate recommended order quantity and urgency level.
Exercise 34: Insurance Claims Adjudicator
Write a claims processing system that: 1. Validates the claim (policy active, coverage period valid, claim amount within limits) 2. Classifies the claim (auto, home, health, life) 3. Applies deductibles and co-pays 4. Checks for pre-existing condition exclusions 5. Determines coverage percentage based on plan tier 6. Calculates the approved amount
Use condition names for policy status, claim types, and plan tiers. Use EVALUATE for the multi-factor coverage determination.
Exercise 35: Academic Transcript Analyzer
Write a program that processes a student's transcript (stored as a table in WORKING-STORAGE) and: 1. Calculates GPA using weighted grade points 2. Determines academic standing (Dean's List, Good Standing, Probation, Suspension) 3. Checks prerequisite satisfaction for next-semester courses 4. Determines graduation eligibility (minimum credits, minimum GPA, required courses)
Use condition names for grade categories and academic standing. Use EVALUATE for GPA-to-letter-grade conversion.
Exercise 36: Network of IF/EVALUATE Optimization
Given the following inefficient code that checks 20 conditions sequentially, restructure it using optimal EVALUATE and IF combinations. Measure the "readability score" by counting nesting levels and total lines:
IF field-1 = "A" AND field-2 > 100 THEN action-1
IF field-1 = "A" AND field-2 <= 100 THEN action-2
IF field-1 = "B" AND field-3 = "X" THEN action-3
IF field-1 = "B" AND field-3 = "Y" THEN action-4
... (16 more similar conditions)
Rewrite using EVALUATE with ALSO, minimizing redundancy and maximizing clarity. Document your design choices.
Exercise 37: Complete Loan Application System
Combining all concepts from this chapter, build a complete loan application evaluation system that includes: 1. Applicant data validation (class conditions, sign conditions) 2. Credit score evaluation (condition names with THRU ranges) 3. Debt-to-income ratio calculation and evaluation 4. Employment stability assessment (EVALUATE TRUE ALSO TRUE) 5. Collateral valuation (for secured loans) 6. Risk score computation (compound conditions) 7. Interest rate determination (multi-factor EVALUATE) 8. Maximum loan amount calculation 9. Monthly payment estimation 10. Final eligibility decision with detailed explanation
This exercise integrates every conditional logic concept from the chapter.
Exercise 38: Self-Testing Exercise Validator
Write a COBOL program that tests itself. Create a test harness that: 1. Defines test cases as data (input values and expected results) 2. Runs each test case through a business logic section 3. Compares actual results to expected results using IF conditions 4. Reports PASS/FAIL for each test 5. Provides a summary with total tests, passed, and failed
Implement the business logic as a simplified version of the loan eligibility checker. Include at least 15 test cases covering boundary conditions, typical cases, and edge cases.
Solutions
Selected solutions are provided in code/exercise-solutions.cob. The file contains complete, compilable solutions for Exercises 1, 3, 5, 8, 10, 14, 18, and 22. Compare your solutions to the provided ones, but remember that there are many correct approaches to each problem.