Chapter 4 Exercises: Input, Output, and Formatting
Part A: Write and WriteLn Basics (Remember/Understand)
Exercise 4.1 — Predict the Output Without running the code, predict the exact output of each program. Then compile and check your predictions.
(a)
program Ex4_1a;
begin
Write('One');
Write('Two');
Write('Three');
WriteLn;
end.
(b)
program Ex4_1b;
begin
WriteLn('Line 1');
WriteLn;
WriteLn('Line 3');
end.
(c)
program Ex4_1c;
var
x: Integer;
begin
x := 5;
WriteLn(x, x, x);
WriteLn(x, ' ', x, ' ', x);
end.
Exercise 4.2 — Write vs. WriteLn
Explain in your own words the difference between Write and WriteLn. Give one specific situation where you would use Write instead of WriteLn, and explain why.
Exercise 4.3 — Multiple Arguments
Write a program that declares three variables — an Integer, a Real, and a String — assigns values to them, and displays all three on a single line using one WriteLn call with multiple arguments. Include labels (e.g., "Name: Alice, Age: 22, GPA: 3.85").
Exercise 4.4 — The Empty WriteLn
Write a program that prints your name, a blank line, your city, two blank lines, and your favorite programming language, each on its own line. Use WriteLn with and without arguments appropriately.
Part B: Formatting Output (Understand/Apply)
Exercise 4.5 — Field Width Exploration
Write a program that prints the integer 42 with field widths of 2, 5, 10, and 20. Use pipe characters (|) to mark the boundaries of each field. Predict the output before running.
Exercise 4.6 — Real Number Formatting
Write a program that stores the value 123.456789 in a Real variable and displays it:
(a) With no formatting (default scientific notation)
(b) With :0:2 (compact, 2 decimal places)
(c) With :10:2 (10-character field, 2 decimal places)
(d) With :10:4 (10-character field, 4 decimal places)
(e) With :0:0 (no decimal places)
Exercise 4.7 — Multiplication Table Write a program that displays a 5x5 multiplication table with neatly aligned columns. Each number should be formatted in a field of width 6. The output should look like:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
(Hint: You do not need loops for this exercise — just 5 WriteLn calls with the right numbers and field widths.)
Exercise 4.8 — Currency Table Write a program that displays the following table with proper alignment. All dollar amounts should have two decimal places. The total should be calculated, not hardcoded.
Monthly Budget Summary
========================
Item Amount
------------------------------
Rent $850.00
Groceries $320.50
Utilities $145.75
Transportation $89.00
Entertainment $60.00
------------------------------
TOTAL $1,465.25
Note: Pascal does not have a built-in way to add commas to numbers. Display the total without the comma — that is fine.
Exercise 4.9 — Receipt Formatter Write a program that declares variables for three items (name, quantity, unit price) and calculates the extended price (quantity * unit price) for each. Display the data as a formatted receipt with a header, item lines, subtotal, tax (8% of subtotal), and grand total. All amounts should be right-aligned and display two decimal places.
Part C: Input and ReadLn (Apply)
Exercise 4.10 — Personal Information
Write a program that asks the user for their first name, last name, age, and favorite number. Display the information in a formatted summary using field widths. Include appropriate prompts with Write.
Exercise 4.11 — Temperature Converter
Write a program that asks the user for a temperature in Fahrenheit and converts it to Celsius using the formula C = (F - 32) * 5 / 9. Display the result with one decimal place. Include a clear prompt and a labeled result.
Exercise 4.12 — Area Calculator
Write a program that asks the user for the length and width of a rectangle (as Real values) and calculates the area and perimeter. Display results with two decimal places and clear labels.
Exercise 4.13 — Read vs. ReadLn Bug Hunt The following program has a bug related to the input buffer. Identify the bug, explain why it occurs, and fix it:
program BugHunt;
var
initial: Char;
name: String;
begin
Write('Enter your first initial: ');
Read(initial);
Write('Enter your full name: ');
ReadLn(name);
WriteLn('Initial: ', initial);
WriteLn('Name: ', name);
end.
Exercise 4.14 — Multi-Value Input
Write a program that asks the user to enter three integers separated by spaces on a single line (e.g., 10 20 30). Read all three with a single ReadLn call. Display each value on its own line with a label, and display their average with two decimal places.
Part D: Input Validation (Apply/Analyze)
Exercise 4.15 — Safe Integer Reader Write a program that asks the user for an integer using the string-then-Val pattern. If the input is not a valid integer, display an error message and ask again. Continue until the user enters a valid integer, then display it.
Exercise 4.16 — Range Validator Extend Exercise 4.15 so that the program not only checks that the input is a valid integer but also that it falls within the range 1 to 100 (inclusive). If the number is valid but out of range, display a specific message like "Number must be between 1 and 100."
Exercise 4.17 — Grade Calculator with Validation Write a program that asks the user for three test scores (Real values, range 0 to 100). Validate each score using Val and range checking. After all three scores are entered, calculate the average and display it formatted to one decimal place.
Exercise 4.18 — Menu Choice Validator Write a program that displays a menu with four options (numbered 1-4) and asks the user to enter their choice. Validate that the input is both a valid integer and within the range 1-4. Display which option the user chose. (You do not need to implement the menu actions — just validate and echo the choice.)
Exercise 4.19 — Val Error Position
Write a program that reads a string from the user, attempts to convert it to a Real using Val, and if the conversion fails, reports not just that it failed but where it failed. For example, if the user types 12.3abc, the program should say something like: "Error at position 5: character 'a' is not valid in a number."
Part E: Design and Synthesis (Apply/Analyze)
Exercise 4.20 — Unit Converter Write a program that converts between miles and kilometers. Ask the user for a distance in miles and display the equivalent in kilometers (1 mile = 1.60934 km). Format the output neatly with appropriate decimal places and labels.
Exercise 4.21 — Tip Calculator Write a program that asks for the bill amount and the desired tip percentage. Calculate the tip amount and total. Display all three values (bill, tip, total) in a formatted summary. Validate that the bill amount is positive and the tip percentage is between 0 and 100.
Exercise 4.22 — Student Report Card Write a program that asks for a student's name, course name, and three assignment scores. Calculate the average, determine the letter grade (A: 90+, B: 80-89, C: 70-79, D: 60-69, F: below 60), and display a formatted report card. Use field widths to align the information.
(Hint: You may need if-then-else from Chapter 5 for the letter grade. If you have not read Chapter 5 yet, just display the average without the letter grade.)
Exercise 4.23 — Formatted Calendar Day Write a program that asks the user for a month name (String), day (Integer), and year (Integer). Display the date in three different formats: - Full: "March 15, 2026" - Numeric: "03/15/2026" (use field widths and leading zeros are not required — e.g., "3/15/2026" is acceptable) - ISO: "2026-03-15" (again, leading zeros optional)
Exercise 4.24 — ASCII Art Banner Write a program that asks the user for a word (up to 10 characters) and displays it inside a box of asterisks:
**************
* *
* PASCAL *
* *
**************
The box should adjust its width to fit the word with 3 spaces of padding on each side. (Hint: use Length(word) to determine the string length.)
Exercise 4.25 — Expense Comparison Write a program that asks the user for two expense amounts and their descriptions. Display them side by side in a formatted comparison table, and indicate which expense is larger (or if they are equal). Calculate and display the difference.
Part M: Mastery Challenge
Exercise 4.26 — Invoice Generator Write a complete invoice program that: 1. Asks for a company name 2. Asks for a customer name 3. Asks for 3 line items (description, quantity, unit price — with validation on quantity and price) 4. Calculates extended price for each line item 5. Calculates subtotal, tax (7.5%), and grand total 6. Displays a complete, professionally formatted invoice with borders, headers, aligned columns, and a footer
The output should look like a real invoice. Use every formatting technique from this chapter: field widths, decimal places, separators, headers, and aligned columns.
Exercise 4.27 — Metric Conversion Dashboard Write a program that acts as a multi-conversion tool. Display a menu of 5 conversion types: 1. Miles to Kilometers 2. Pounds to Kilograms 3. Fahrenheit to Celsius 4. Gallons to Liters 5. Inches to Centimeters
Ask the user to choose a conversion type (with validation) and then enter a value (with validation). Display the result formatted to 4 decimal places and also to 2 decimal places. Display both the original and converted values with their units in a formatted summary box.
Exercise 4.28 — Table of Powers Write a program that displays a table showing the integers 1 through 10 along with their squares, cubes, and fourth powers. All columns should be right-aligned with appropriate field widths, and the table should have a header row and separator lines. The fourth power of 10 is 10,000 — make sure your field widths accommodate the largest values.
Exercise 4.29 — Interactive Budget Planner Write a program that asks the user for their monthly income and then asks for amounts in 6 expense categories (housing, food, transportation, utilities, entertainment, savings). Validate each input. Display a formatted budget summary table showing each category, its amount, and its percentage of total income. At the bottom, show the amount remaining (income minus total expenses) and whether the budget is balanced, over, or under.
Exercise 4.30 — Mini Database Display Write a program that declares variables for 4 "records" (students), each with a name (String), ID number (Integer), and GPA (Real). Assign hardcoded values. Display all 4 records in a neatly formatted table with headers, separators, a row count at the bottom, and the class average GPA. The GPA column should show exactly 2 decimal places. The ID column should be 8 characters wide. The name column should be 20 characters wide.