Chapter 5 Exercises: Basic Input/Output and DISPLAY/ACCEPT Statements

These exercises are organized into five tiers of increasing difficulty. Complete all exercises in a tier before moving to the next. Solutions to selected exercises (marked with *) are provided in code/exercise-solutions.cob.


Tier 1: Fundamentals (Exercises 1-5)

These exercises practice the basic mechanics of DISPLAY and ACCEPT.


Exercise 1 * -- Personal Greeting

Write a program that: 1. Asks the user for their first name 2. Asks the user for their age 3. Displays a greeting message such as: "Hello, GRACE! You are 85 years old. Welcome to COBOL programming!"

Requirements: - Use WITH NO ADVANCING for the prompts - Use an edited picture (zero-suppressed) to display the age without leading zeros

Expected interaction:

What is your name? Grace
How old are you? 28

Hello, Grace! You are  28 years old.
Welcome to COBOL programming!

Exercise 2 -- Three-Line Display

Write a program that displays the following output using only DISPLAY statements and WORKING-STORAGE fields. Do not use any literal strings in the PROCEDURE DIVISION -- define all text as VALUE clauses in WORKING-STORAGE.

============================================
  COBOL FUNDAMENTALS - CHAPTER 5
  BASIC INPUT/OUTPUT STATEMENTS
============================================

Hint: Define a separator line with PIC X(44) VALUE ALL "=" and title lines with FILLER.


Exercise 3 * -- Current Date Display

Write a program that: 1. Retrieves the current date using ACCEPT FROM DATE YYYYMMDD 2. Displays the date in MM/DD/YYYY format (US format) 3. Does not accept any user input

Expected output:

Today's date is: 02/10/2026

Exercise 4 -- Multiple DISPLAY Variations

Write a program that demonstrates all of the following in a single execution: 1. A literal string display 2. A numeric literal display 3. A figurative constant display (SPACES) 4. A variable display 5. A concatenated display (literal + variable) 6. A WITH NO ADVANCING display followed by another display on the same line 7. A display using ALL to fill a line with a character

Label each output section clearly.


Exercise 5 -- Day of the Week

Write a program that: 1. Accepts the current day of the week using ACCEPT FROM DAY-OF-WEEK 2. Uses EVALUATE to convert the number to a day name 3. Displays a message like: "Today is Tuesday. Have a productive day!" 4. If the day is Saturday or Sunday, display: "Today is Saturday. Enjoy your weekend!"


Tier 2: Applied Basics (Exercises 6-10)

These exercises combine DISPLAY and ACCEPT with data manipulation.


Exercise 6 -- Full Date and Time Report

Write a program that displays a complete date/time report including: - Current date in YYYY-MM-DD format - Current date in DD/MM/YYYY format (European) - Current time in HH:MM:SS format (24-hour) - Current Julian day (day of year) - Day of week name

Format all output in a bordered box using dashes and pipes.


Exercise 7 -- Simple Address Form

Write a program that accepts a complete mailing address from the user: - Full name (PIC X(30)) - Street address (PIC X(40)) - City (PIC X(20)) - State/Province (PIC X(2)) - ZIP/Postal code (PIC X(10))

After accepting all fields, display the formatted address label:

+------------------------------------+
|  JOHN Q. PUBLIC                    |
|  123 MAIN STREET APT 4B           |
|  SPRINGFIELD, IL 62701             |
+------------------------------------+

Exercise 8 * -- Date Components

Write a program that retrieves the system date and displays every component separately: - Full date (YYYYMMDD) - Year - Month number - Month name (use a table of month names) - Day of month - Day of week number - Day of week name (use a table)

Expected output:

Date Components:
  Full Date (YYYYMMDD): 20260210
  Year:                 2026
  Month Number:         02
  Month Name:           February
  Day of Month:         10
  Day of Week Number:   2
  Day of Week Name:     Tuesday

Exercise 9 -- Multiplication Table

Write a program that: 1. Asks the user for a number (1-12) 2. Displays the multiplication table for that number, formatted with column alignment

Expected output (if user enters 7):

MULTIPLICATION TABLE FOR 7
===========================
  7 x  1 =    7
  7 x  2 =   14
  7 x  3 =   21
  ...
  7 x 12 =   84
===========================

Use edited pictures to right-align the results.


Exercise 10 -- Environment Variable Reader

Write a program that: 1. Asks the user for an environment variable name 2. Attempts to read that environment variable 3. Displays the value or a "not found" message

Allow the user to check multiple variables in a loop until they type "QUIT".


Tier 3: Intermediate (Exercises 11-17)

These exercises build more complex interactive programs.


Exercise 11 -- Receipt Generator

Write a program that simulates a store receipt: 1. Accept the store name 2. Accept up to 5 items (item name and price for each) 3. Ask after each item: "Add another item? (Y/N)" 4. Calculate the subtotal 5. Calculate tax at 8.25% 6. Display a formatted receipt:

====================================
        ACME GENERAL STORE
        02/10/2026  14:30:22
------------------------------------
  Bread                    $   3.49
  Milk                     $   4.99
  Eggs                     $   5.29
------------------------------------
  Subtotal:                $  13.77
  Tax (8.25%):             $   1.14
  ================================
  TOTAL:                   $  14.91
====================================
  Thank you for shopping with us!
====================================

Exercise 12 * -- Invoice Line Display

Write a program that: 1. Accepts an item name, quantity, and unit price 2. Calculates the line total (quantity * unit price) 3. Displays a formatted invoice line with proper column headers

Use structured record lines with FILLER for alignment.


Exercise 13 -- Number Guessing Game

Write an interactive guessing game: 1. Hardcode a "secret number" between 1 and 100 (or use the system time's hundredths to generate a pseudo-random one) 2. Let the user guess repeatedly 3. After each guess, display "Too high!", "Too low!", or "Correct!" 4. Track the number of guesses 5. When correct, display: "You guessed it in X tries!" 6. Ask "Play again? (Y/N)"


Exercise 14 -- Unit Converter

Write a menu-driven unit conversion program: 1. Display a menu: Length, Weight, Temperature 2. For Length: miles to kilometers, feet to meters, inches to centimeters 3. For Weight: pounds to kilograms, ounces to grams 4. For Temperature: Fahrenheit to Celsius, Celsius to Fahrenheit 5. Accept the source value, perform the conversion, display the result with appropriate units 6. Return to the main menu after each conversion

Use edited pictures for all numeric output.


Exercise 15 -- Student Grade Report

Write a program that: 1. Accepts a student name 2. Accepts scores for 5 subjects (English, Math, Science, History, Art) 3. Calculates the average 4. Determines the letter grade (A: 90+, B: 80-89, C: 70-79, D: 60-69, F: below 60) 5. Displays a formatted grade report card

================================================
           STUDENT GRADE REPORT
================================================
  Student: JANE SMITH
  Date:    02/10/2026
------------------------------------------------
  Subject          Score    Grade
  --------         -----    -----
  English            92      A
  Mathematics        85      B
  Science            78      C
  History            91      A
  Art                88      B
------------------------------------------------
  Average:         86.80     B
================================================

Exercise 16 * -- Simple Login Screen

Write a program that: 1. Displays a login box with a border 2. Accepts a username and password 3. Validates against hardcoded credentials (ADMIN / COBOL2026) 4. Allows 3 attempts before displaying an "account locked" message 5. On successful login, displays a welcome message with the current date and time


Exercise 17 -- Multi-Page Display

Write a program that displays a long list of data (at least 30 items) with pagination: 1. Display 10 items per "page" 2. After each page, display "Page X of Y -- Press Enter for next page" 3. Use a table of data defined in WORKING-STORAGE (for example, a list of countries and capitals) 4. Allow the user to press Enter to advance or type "Q" to quit


Tier 4: Advanced (Exercises 18-23)

These exercises require combining multiple concepts.


Exercise 18 -- Mini Spreadsheet

Write a program that: 1. Accepts a 3x3 grid of numbers from the user 2. Displays the grid in a formatted table 3. Calculates and displays row totals, column totals, and the grand total

+--------+--------+--------+--------+
|  Col 1 |  Col 2 |  Col 3 |  TOTAL |
+--------+--------+--------+--------+
|    120 |    340 |    250 |    710 |
|    415 |    180 |    390 |    985 |
|    200 |    275 |    310 |    785 |
+--------+--------+--------+--------+
|    735 |    795 |    950 |  2,480 |
+--------+--------+--------+--------+

Exercise 19 -- Contact Directory

Write a program that manages a simple in-memory contact directory: 1. Add a contact (name, phone, email) -- store up to 10 contacts in a table 2. List all contacts in a formatted display 3. Search for a contact by name (partial match using INSPECT or simple comparison) 4. Delete a contact by number 5. Menu-driven with proper navigation


Exercise 20 * -- Tip Calculator

Write a restaurant tip calculator that: 1. Accepts the bill amount 2. Accepts the number of diners 3. Calculates tips at 15%, 18%, and 20% 4. For each percentage, displays: tip amount, total with tip, and per-person amount 5. Displays results in a formatted table with borders


Exercise 21 -- Countdown Timer Display

Write a program that: 1. Accepts a number of seconds from the user (1-60) 2. Displays a countdown from that number to zero 3. Uses ACCEPT FROM TIME repeatedly to detect when one second has elapsed 4. Displays "Time's up!" at the end

Hint: Convert the time to total seconds and compare.


Exercise 22 -- Screen Section Form (GnuCOBOL)

Using the SCREEN SECTION, create a data entry form for a product catalog: - Product ID (6 digits) - Product Name (30 characters) - Category (15 characters) - Unit Price (formatted with currency) - Quantity in Stock (5 digits) - Reorder Level (5 digits)

Use colors and attributes to distinguish labels from input fields. Display a summary screen after entry.


Exercise 23 -- Batch Report Simulator

Write a program that simulates batch report generation: 1. Define 20 hardcoded records in WORKING-STORAGE (a table of products with ID, name, category, price, and quantity) 2. Generate a formatted report to the console with: - Report header with date and page number - Column headers - Detail lines for each record - Subtotals by category (assume 3-4 categories) - Grand total at the bottom - Page break every 15 lines (re-display headers) 3. Show record count and processing time at the end


Tier 5: Expert Challenges (Exercises 24-28)

These exercises push the boundaries of console I/O.


Exercise 24 -- Text-Based Dashboard

Create a console dashboard that displays on a single screen: - Current date and time (refreshed each cycle) - System summary area (simulated: CPU usage, memory, disk) - A "log" area showing the last 5 "events" (simulated) - Navigation bar at the bottom

Use the SCREEN SECTION with colors to create visual sections. Allow the user to press Enter to refresh or type "Q" to quit.


Exercise 25 * -- Elapsed Time Calculator

Write a program that: 1. Records the current system time at the start 2. Waits for the user to press Enter 3. Records the current system time at the end 4. Calculates and displays the elapsed time in seconds 5. Handles the case where the time crosses midnight (optional)

Use ACCEPT FROM TIME for both timestamps and convert to total seconds for subtraction.


Exercise 26 -- Interactive Quiz Engine

Build a quiz program that: 1. Stores 10 multiple-choice questions in WORKING-STORAGE tables 2. Each question has 4 options (A-D) and one correct answer 3. Presents questions one at a time 4. Accepts the user's answer 5. Provides immediate feedback (correct/incorrect, showing the right answer) 6. Tracks the score 7. At the end, displays a scorecard with percentage and grade

Make the questions about COBOL (from chapters 1-4) for a self-reinforcing learning experience.


Exercise 27 -- ASCII Art Generator

Write a program that: 1. Accepts a word from the user (up to 10 characters) 2. Displays the word in large "block letters" made of the character itself

Example for input "HI":

H   H  IIIII
H   H    I
HHHHH    I
H   H    I
H   H  IIIII

Define the block patterns for at least the letters A-Z in a WORKING-STORAGE table.

Hint: Use a 5-row by 5-column grid for each letter.


Exercise 28 -- ATM Interface Enhancement

Extend the ATM simulator from the case study to include: 1. Fund transfer between checking and savings (simulate two accounts) 2. Transaction history display (store last 10 transactions in a table) 3. PIN change functionality (accept old PIN, then new PIN twice for confirmation) 4. Daily withdrawal limit tracking ($500/day) 5. Formatted receipts with a transaction reference number 6. A "fast cash" option with preset amounts ($20, $40, $60, $100, $200)


Exercise Submission Checklist

For each exercise, verify:

  • [ ] Program compiles without errors (cobc -x program.cob)
  • [ ] Program runs and produces correct output
  • [ ] All numeric output uses edited PICTURE clauses (no raw leading zeros)
  • [ ] All prompts use WITH NO ADVANCING
  • [ ] Input validation is present where appropriate
  • [ ] Column alignment is consistent in tabular output
  • [ ] Program terminates cleanly with STOP RUN or GOBACK
  • [ ] Source code follows fixed-format column rules
  • [ ] Comments explain the purpose of each section
  • [ ] Variable names follow the WS- prefix convention

Bonus Challenge

The Self-Documenting Program: Write a COBOL program that, when executed, displays its own source code. The program must read its own source file using file I/O (preview of Chapter 11) or, alternatively, store its source code in WORKING-STORAGE variables and display them. This exercise bridges console I/O with the upcoming file I/O chapters.