๐Ÿ›๏ธ

Delphi / Object Pascal Cheat Sheet

A structured, strongly-typed descendant of classic Pascal โ€” still running huge amounts of enterprise Windows desktop software (banking, healthcare, manufacturing systems) built in the '90s and 2000s that never got rewritten. Copy-paste examples plus live Run/Submit exercises.

Jump to: Your first programVariablesif / else LoopsArraysProcedures & functions ๐Ÿš€ Practice problems

Your first program

program Hello;
begin
  writeln('Hello, world!');
end.
๐Ÿ“ Every Pascal program ends with a period after the final end โ€” easy to forget, and the compiler will refuse to build without it.

Variables

var
  age: Integer;
  name: String;
  price: Real;
begin
  age := 25;
  name := 'Sam';
  price := 19.99;
end.
๐Ÿ“ All variables must be declared up front in a var block โ€” Pascal doesn't let you declare mid-code like most modern languages.

if / else

if age >= 18 then
  writeln('Adult')
else if age >= 13 then
  writeln('Teen')
else
  writeln('Child');

Loops

var i, n: Integer;
begin
  for i := 1 to 5 do
    writeln(i);

  n := 3;
  while n > 0 do
  begin
    writeln(n);
    n := n - 1;
  end;
end.

Arrays

var
  nums: array[0..4] of Integer;
  i: Integer;
begin
  nums[0] := 10;
  nums[1] := 20;
  for i := 0 to 1 do
    writeln(nums[i]);
end.

Procedures & functions

Pascal separates the two โ€” procedure does something, function returns a value.

function Add(a, b: Integer): Integer;
begin
  Add := a + b;
end;

begin
  writeln(Add(3, 4));
end.

๐Ÿš€ Practice problems

Full runnable programs, compiled and run in a real Free Pascal sandbox โ€” same workspace as the other cheat sheets.

Sum an array EASY

var
  nums: array[0..5] of Integer = (4, 8, 15, 16, 23, 42);
  sum, i: Integer;
begin
  sum := 0;
  for i := 0 to 5 do
    sum := sum + nums[i];
  writeln(sum);
end.

Reverse a string MEDIUM

function ReverseStr(s: String): String;
var
  i: Integer;
  result: String;
begin
  result := '';
  for i := length(s) downto 1 do
    result := result + s[i];
  ReverseStr := result;
end;

begin
  writeln(ReverseStr('pascal'));
end.

FizzBuzz MEDIUM

var i: Integer;
begin
  for i := 1 to 15 do
  begin
    if i mod 15 = 0 then
      writeln('FizzBuzz')
    else if i mod 3 = 0 then
      writeln('Fizz')
    else if i mod 5 = 0 then
      writeln('Buzz')
    else
      writeln(i);
  end;
end.

Count vowels in a string HARD

var
  text: String = 'the quick brown fox';
  i, count: Integer;
begin
  count := 0;
  for i := 1 to length(text) do
    if pos(text[i], 'aeiouAEIOU') > 0 then
      count := count + 1;
  writeln(count);
end.