Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Pascal Practice Set

Twelve graded Pascal and Delphi exercises on units, classes, files and databases, with hints, worked solutions for three of them and a runnable C check of the logic.

Reading is not enough. You learn Pascal by writing it, getting compiler errors, and fixing them. This final lesson gives you twelve exercises that follow the chapters of this course: units, classes and properties, files and databases, and forms. Three of them have worked solutions that you can compare with your own. The rest have hints.

Do these in Delphi (the Community Edition is free for learners) or in Free Pascal and Lazarus. The browser cannot compile Pascal, so the worked solutions are read-only. The C program in the middle runs the same algorithms so you can check your expected results.

How to practice

  1. Try the exercise for at least fifteen minutes before looking at a hint.
  2. Make it compile, then make it correct, then make it tidy.
  3. Test the edge cases: empty input, zero, the largest value, a missing file.
  4. Compile with range and overflow checking on (see debugging and compiler tools).
  5. Free every object you create. Use ReportMemoryLeaksOnShutdown := True to check.

The exercises

Level 1: units and procedures

  1. StringUtils unit. Write a unit with Reverse(const S: string): string, IsPalindrome (ignore case and spaces) and CountWords. Keep helper routines in the implementation section only. See units and the uses clause.
  2. Initialization log. Write two units, Logger and Config, where Config uses Logger. Each prints a line in initialization and finalization. Predict the order before running. See initialization and finalization.
  3. Generic Stack. Write TStack<T> with Push, Pop, Peek and Count, using a TList<T> inside, and raise an exception when popping an empty stack. See generics and anonymous methods.

Level 2: classes

  1. TTemperature class. Store the value in Celsius. Add properties Celsius, Fahrenheit and Kelvin where the last two compute from the first, and a setter that rejects values below absolute zero. See properties and visibility.
  2. Shape hierarchy. An abstract TShape with Area and Perimeter, descendants TCircle, TRectangle and TTriangle (use Heron's formula). Put ten shapes in a TObjectList<TShape> and print the one with the largest area. See inheritance and virtual methods.
  3. Custom exceptions. Add EInvalidShape to exercise 5 and raise it for negative sizes or for a triangle that violates the triangle inequality. Catch it in the program and print E.Message. See interfaces and exceptions.

Level 3: files and data

  1. Word counter. Read a text file into a TStringList, split it into words, and print the ten most frequent words. Hint: a TDictionary<string, Integer> and then sort the pairs. See text files and TStringList.
  2. Student file. Store TStudent records (name, three marks) in a typed file. Write procedures to add, list, change the second mark of record N and compute each average. See typed files and streams.
  3. Streams. Write CopyFileWithProgress that copies a file with TFileStream in 64 KB chunks and calls an OnProgress(Percent: Integer) event. Reuse the event pattern from events and the IDE.
  4. Library database. With SQLite and FireDAC, create tables authors and books, insert sample data using parameters, and print each author with the number of their books using a JOIN and GROUP BY. See databases with FireDAC.

Level 4: forms and projects

  1. Calculator form. Build a VCL form with two edits, four operator buttons that share ONE event handler (use Sender), and a label showing the result. Show an error message instead of crashing on invalid input or division by zero. See VCL forms and components.
  2. Finish a project. Extend the contact book with a TListView, an edit panel and CSV export, or add inventory and a second goal to the text adventure.

Worked solutions

Exercise 1: IsPalindrome

PASCAL
function IsPalindrome(const S: string): Boolean;
var
  Clean: string;
  I, J: Integer;
  Ch: Char;
begin
  Clean := '';
  for Ch in S do
    if Ch.IsLetterOrDigit then
      Clean := Clean + LowerCase(Ch);
  I := 1;
  J := Length(Clean);
  Result := True;
  while I < J do
  begin
    if Clean[I] <> Clean[J] then
      Exit(False);
    Inc(I);
    Dec(J);
  end;
end;

Strings are 1-based in Delphi and Free Pascal. The two indexes walk toward each other. The Exit(False) form returns a value and leaves at once.

Exercise 4: Fahrenheit property

PASCAL
function TTemperature.GetFahrenheit: Double;
begin
  Result := FCelsius * 9 / 5 + 32;
end;

procedure TTemperature.SetFahrenheit(const Value: Double);
begin
  SetCelsius((Value - 32) * 5 / 9);   // reuse the validating setter
end;

procedure TTemperature.SetCelsius(const Value: Double);
begin
  if Value < -273.15 then
    raise EArgumentOutOfRangeException.CreateFmt('%.2f is below absolute zero', [Value]);
  FCelsius := Value;
end;

Only FCelsius is stored; the others are computed. All writes go through one setter, so the rule cannot be bypassed.

Exercise 7: word frequencies, the algorithm

Because we cannot run Pascal here, the program below does the same job in C and prints deterministic results: normalise words to lowercase, count them, then print the most frequent first. In Delphi, TDictionary<string, Integer> replaces the array search.

C Stand-in: count and rank words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Try adding "the" and "a" to a stop-word list that count_word skips. In Pascal, a set of string is not possible, but a TStringList with Sorted := True and IndexOf works as a stop-word set.

Common stumbling blocks

  • Forgetting Free on objects created without an owner. Use try..finally.
  • Off-by-one errors between 0-based dynamic arrays and 1-based strings.
  • = versus :=. Comparison is =, assignment is :=.
  • Using a property setter's own name inside it, which calls itself forever.
  • No semicolon before else. In if A then B else C there must be no ; after B.
  • Long event handlers that freeze the form.

Where to go next

You now know the core of Object Pascal: units, classes, properties, files, databases and forms. Good next steps are to learn the FireMonkey (FMX) framework for mobile and macOS apps, the REST client components for web services, unit testing with DUnitX, and the Free Pascal documentation if you want portable command-line tools. Return to the Pascal and Delphi track page any time to review a chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Exit(False) do inside a function?

    Exit with a value assigns the result and returns immediately.
  2. 2. In if A then B else C, where must the semicolon NOT appear?

    A semicolon before else ends the if statement, so else becomes a syntax error.
  3. 3. Which tool tells you about objects you forgot to free in Delphi?

    FastMM prints a list of leaked objects at shutdown when this flag is set.
  4. 4. Why store only Celsius in the TTemperature class?

    A single source of truth cannot disagree with itself, and every write goes through one validated setter.

Summary

  • Practice in increasing difficulty: units, classes, exceptions, files, databases, forms.
  • Make code compile, then correct, then tidy; test edge cases with range and overflow checks on.
  • Keep one source of truth, free what you create and validate in setters.
  • Finish a real project: that is where the pieces finally fit together.

Next: Pascal and Delphi track