Chapter 11 Exercises: Records and Variant Records

Part A — Comprehension (Short Answer)

Exercise 11.1 What problem do records solve that arrays cannot? Give two specific limitations of using parallel arrays that records eliminate.

Exercise 11.2 Explain the difference between a record type and a record variable. Where in a Pascal program is each declared?

Exercise 11.3 Why does Pascal not allow direct comparison of two record variables using =? How should you compare records instead?

Exercise 11.4 List three reasons why the WITH statement should be used sparingly. What is the scope ambiguity problem?

Exercise 11.5 In a variant record, what is the "tag field" (discriminant)? Why is it important to always check the tag field before accessing variant fields?

Exercise 11.6 Explain how memory is allocated for a variant record. If one variant needs 4 bytes and another needs 20 bytes, how much memory does the compiler allocate for the variant part?

Exercise 11.7 What is the difference between passing a record by value, by reference (var), and by const? When should you use each?


Part B — Tracing and Analysis

Exercise 11.8 Trace the following code and state the final output:

type
  TPoint = record
    X, Y: Integer;
  end;

var
  A, B: TPoint;
begin
  A.X := 3;
  A.Y := 7;
  B := A;
  B.X := B.X + 10;
  A.Y := A.Y * 2;
  WriteLn(A.X, ' ', A.Y, ' ', B.X, ' ', B.Y);
end.

Exercise 11.9 Trace the following code. What does it print? Is there a potential problem?

type
  TRec = record
    Name: string;
    Value: Integer;
  end;

var
  R: TRec;
  Name: string;
begin
  Name := 'Global';
  R.Name := 'Record';
  R.Value := 42;
  with R do
  begin
    Name := 'Changed';
    WriteLn(Name, ' ', Value);
  end;
  WriteLn(Name);
end.

Exercise 11.10 The following code has a bug. Identify it and explain how to fix it:

type
  TGradeArray = array[1..10] of Integer;

  TStudent = record
    Name: string;
    Grades: TGradeArray;
    Count: Integer;
  end;

var
  Students: array[1..5] of TStudent;
begin
  Students[1].Name := 'Alice';
  Students[1].Grades[1] := 95;
  Students[1].Count := 1;

  if Students[1] = Students[2] then
    WriteLn('Same student');
end.

Exercise 11.11 Trace the output of this variant record code:

type
  TKind = (kInt, kReal, kStr);
  TValue = record
    case Kind: TKind of
      kInt: (IntVal: Integer);
      kReal: (RealVal: Real);
      kStr: (StrVal: string[20]);
  end;

var
  V: TValue;
begin
  V.Kind := kInt;
  V.IntVal := 42;
  WriteLn(V.IntVal);

  V.Kind := kReal;
  V.RealVal := 3.14;
  WriteLn(V.RealVal:0:2);
end.

Part C — Focused Coding

Exercise 11.12 Define a record type TBook with fields for Title (string), Author (string), Year (Integer), Pages (Integer), and Price (Real). Write a procedure PrintBook that takes a const TBook parameter and prints all fields in a formatted display.

Exercise 11.13 Write a function CreateBook that takes title, author, year, pages, and price as parameters and returns a TBook record with all fields populated.

Exercise 11.14 Define an array of up to 100 TBook records. Write a procedure FindCheapest that takes the array and a count, and returns the index of the book with the lowest price.

Exercise 11.15 Define a TDateRec record with Day, Month, and Year fields (all Integer). Write a function IsValidDate that takes a const TDateRec and returns True if the date is valid (correct day range for the given month, accounting for leap years).

Exercise 11.16 Write a procedure SortBooksByYear that sorts an array of TBook records in ascending order by Year. Use any sorting algorithm you know.

Exercise 11.17 Define nested records for a TContact that contains a TName record (with First, Middle, Last fields) and a TPhone record (with CountryCode, AreaCode, Number fields). Write a procedure that prints a contact in the format: "Last, First M. — +1 (555) 123-4567".

Exercise 11.18 Define a variant record TVehicle with a common Make (string), Model (string), and Year (Integer), and a tag field Kind of type TVehicleKind = (vkCar, vkTruck, vkMotorcycle). Cars have NumDoors: Integer; trucks have PayloadTons: Real and NumAxles: Integer; motorcycles have EngineCC: Integer. Write a procedure that prints a vehicle's details based on its kind.


Part D — Problem Solving

Exercise 11.19 — Student Roster Manager Write a complete program that manages a roster of up to 50 students. Each student has a Name (string), ID (Integer), and three exam scores (array[1..3] of Integer). The program should support: 1. Adding a student 2. Displaying all students with their average score 3. Finding the student with the highest average 4. Searching for a student by ID

Use a menu-driven loop.

Exercise 11.20 — Weather Station Records Define a TWeatherDay record with fields: Date (string), HighTemp (Real), LowTemp (Real), Precipitation (Real), and Sunny (Boolean). Write a program that: 1. Reads weather data for 7 days 2. Calculates the average high and low temperatures for the week 3. Finds the day with the most precipitation 4. Counts the number of sunny days 5. Determines the day with the greatest temperature range (high minus low)

Exercise 11.21 — Library Catalog with Variant Records Define a variant record TLibraryItem that can represent books, magazines, or DVDs. All items share Title (string), ItemID (Integer), and CheckedOut (Boolean). Books have Author and ISBN; magazines have IssueMonth, IssueYear, and Publisher; DVDs have Director, RuntimeMinutes, and Rating. Write a program that stores up to 100 items and supports: 1. Adding items of any type 2. Checking out / returning items 3. Searching by title 4. Displaying all items of a specific type

Exercise 11.22 — Nested Record Address Book Design a TContactEntry record that nests a TFullName (First, Last: string), a TAddress (Street, City, State, Zip: string), and a TPhoneNumber (AreaCode, Number: string). Write a program that stores up to 200 contacts and supports adding, searching by last name, and displaying all contacts sorted alphabetically by last name.

Exercise 11.23 — PennyWise Extension: Budget Tracking Extend the PennyWise checkpoint code to include budget tracking. Add a TCategoryRec with Name, Budget (monthly limit), and TotalSpent. When the user adds an expense, automatically update the category's TotalSpent. Add a "Budget Report" feature that shows each category's budget, amount spent, remaining balance, and a warning if the category is over budget.


Part E — Challenge Problems

Exercise 11.24 — Crypts of Pascalia: Full Item System Build a complete item system for Crypts of Pascalia. Define TItem as a variant record with kinds: ikWeapon, ikArmor, ikPotion, ikKey, ikTreasure. Implement: 1. A global items array (up to 200 items) 2. A player record with an inventory (array of item indices, max 20) 3. Procedures: PickUpItem, DropItem, UseItem, ListInventory 4. UseItem should behave differently for each item kind (weapons deal damage, potions heal, keys unlock) 5. A simple interactive loop where the player can pick up, drop, and use items

Exercise 11.25 — Polynomial Records Define a record TPolynomial with an array of up to 20 real coefficients and a Degree field. Write functions to: 1. Evaluate a polynomial at a given x value 2. Add two polynomials (return a new TPolynomial) 3. Multiply two polynomials (return a new TPolynomial) 4. Print a polynomial in standard mathematical notation (e.g., "3.0x^2 + 1.5x - 2.0")

Exercise 11.26 — Database Simulation Simulate a simple flat-file database. Define a TFieldDef variant record that can be an integer field, a real field, or a string field. Define a TRecord as an array of up to 10 TFieldDef values. Define a TTable as an array of up to 100 TRecord entries plus an array of field names. Implement: 1. Creating a table with a schema (field names and types) 2. Inserting a record 3. Displaying all records in tabular format 4. Filtering records where a specified integer field exceeds a given value


Part M — Metacognitive Reflection

Exercise 11.M1 Before this chapter, how would you have stored information about 50 students, each with a name, ID, and three exam scores? How would you store it now? Write both approaches and compare them in terms of clarity, safety, and ease of modification.

Exercise 11.M2 The WITH statement trades brevity for potential ambiguity. Think of a situation in your own coding where you prioritized brevity over clarity, or vice versa. What was the outcome? How does this inform your approach to WITH?

Exercise 11.M3 Variant records let us store different "shapes" of data in a single type. Can you think of three real-world data domains (outside the examples in this chapter) where data naturally comes in variants? For each, identify the common fields and the variant-specific fields.

Exercise 11.M4 Rate your confidence (1–5) on each learning objective from this chapter: 1. Defining record types with multiple fields 2. Using dot notation and the WITH statement 3. Creating and working with arrays of records 4. Using variant records with tag fields 5. Nesting records within records

For any objective rated 3 or below, write a specific plan for how you will strengthen that skill (re-read a section, write practice code, etc.).