1D Arrays Grade 11

Imagine you need to store 30 student marks. Without arrays you would need 30 separate variables — iMark1, iMark2, … iMark30. With an array, one name stores them all: arrMarks[1..30]. Arrays are a Grade 11 Term 1 topic.

T1Term 1 · 1D Arrays & Array Algorithms

Why Use Arrays?

Without Arrays var iMark1, iMark2, iMark3, iMark4, iMark5, iMark6, iMark7, iMark8, iMark9, iMark10, iMark11, iMark12, iMark13, iMark14, iMark15, iMark16, iMark17, iMark18, iMark19, iMark20, iMark21, iMark22, iMark23, iMark24, iMark25, iMark26, iMark27, iMark28, iMark29, iMark30 : Integer; 30 separate variables — hard to loop over! With Arrays var arrMarks : array[1..30] of Integer; // Loop through all 30 with 3 lines: for i := 1 to 30 do iTotal := iTotal + arrMarks[i]; One name, 30 values, loops work perfectly!

What is a 1D Array?

A one-dimensional array is a structured data type that stores a fixed number of values of the same data type under a single variable name, with each individual value accessed using its own index (a whole number giving that value's position in the list).

ANALOGY — an array is a dinner set

Think of an array like a train: each carriage (box) holds one value and is numbered by its index — the index tells you exactly where to find that value.

Remember a single variable is one cup. An array is a whole matching dinner set — say 6 cups — that all share one name and are numbered: arrCups[1], arrCups[2] … arrCups[6]. Every item is the same type (all cups), just at a different index (place-setting number).

So instead of naming 30 separate cups cup1, cup2, …, you keep one name and pick the one you want by its number: arrMarks[7] is simply "the mark at place setting 7".

arrNames : array[1..7] of String Index [1] Index [2] Index [3] Index [4] Index [5] Index [6] Index [7] 'Alice' 'Bob' 'Callie' 'David' 'Eve' 'Farai' 'Gio' arrNames[3] = 'Callie' · arrNames[1] = 'Alice' · To access last: arrNames[7]

Declaring an Array

Syntax
arrName : array [lowerIndex..upperIndex] of DataType;
Examples
var
  arrNames  : array [1..30] of String;
  arrMarks  : array [1..30] of Integer;
  arrPrices : array [0..9]  of Real;

Arrays of Unknown Length — use a constant

You don't always know in advance exactly how many items you will store. A common trick is to declare a constant for the maximum size, then use it as the upper index. If the size needs to change later, you only edit one line.

Declare the constant BEFORE the array

The constant must be declared above the array declaration (it can go just above type in the interface section), otherwise Delphi won't know what Max means yet.

Delphi
const
  Max = 100;                          // maximum possible learners
var
  arrNames : array [1..Max] of String;
  iCount   : Integer;                  // how many are ACTUALLY used

Keep a separate counter (iCount) for how many elements are really in use, and loop 1 to iCount instead of 1 to Max.

Dynamic Arrays

A dynamic array has no fixed size when declared — you set (and can later change) its length while the program runs with SetLength. This is perfect when the number of items is only known at runtime (e.g. after reading a file).

Dynamic arrays start at index 0

Unlike array[1..30], a dynamic array is always 0-based. If you SetLength(arr, 5) the valid indexes are 0,1,2,3,4. Use Low(arr) for the first index (0) and High(arr) for the last (length − 1).

RoutinePurpose
SetLength(arr, n)Sets (or changes) the array to hold n elements
Length(arr)Returns the current number of elements
Low(arr)First valid index (always 0 for dynamic arrays)
High(arr)Last valid index (Length − 1)
Delphi — dynamic array
var
  arrNum : array of Integer;   // note: NO index range given
  i : Integer;
begin
  SetLength(arrNum, 5);          // now holds 5 ints, index 0..4

  for i := Low(arrNum) to High(arrNum) do
    arrNum[i] := i * 2;           // 0, 2, 4, 6, 8

  SetLength(arrNum, 8);          // grow to 8 — existing values are kept
end;

Populating an Array

Method 1: Fixed values

Delphi
arrNames[1] := 'Alice';
arrNames[2] := 'Bob';
arrNames[3] := 'Callie';

Method 2: Constant array (known at compile time)

Delphi
const
  arrDays : array [1..7] of String =
    ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');

Method 3: User input with a loop

Delphi
for i := 1 to 30 do
  arrNames[i] := InputBox('Name', 'Enter name:', '');

Displaying & Calculating

Delphi
// Display all
for i := 1 to Length(arrMarks) do
  memOut.Lines.Add(IntToStr(arrMarks[i]));

// Sum and average
iTotal := 0;
for i := 1 to Length(arrMarks) do
  iTotal := iTotal + arrMarks[i];
rAvg := iTotal / Length(arrMarks);

Shortcut: the Math Unit

Writing your own loop to total or average an array works, but Delphi's Math unit already has ready-made functions that do the same job in one line.

FunctionReturns
Sum(arr)Total of every element
Mean(arr)Average of every element
MaxValue(arr)The largest value in the array
MinValue(arr)The smallest value in the array
Delphi — Math unit shortcuts
uses Math;   // add this to the uses clause first

rAvg     := Mean(arrPrices);
rTotal   := Sum(arrPrices);
rHighest := MaxValue(arrPrices);
rLowest  := MinValue(arrPrices);
Only for arrays of type Double

These four functions only accept an array whose elements are declared as Double — not Integer, and not the general-purpose Real. If your array holds integers, either redeclare it as array[1..n] of Double, or stick to your own loop.

Arrays with Meaningful Indices

Every index used so far has just meant "the Nth item in the list" — arrNames[3] is simply whoever happens to be third. Sometimes, though, it's more useful to let the index itself carry meaning. If arrVotes[4] always holds the vote count for competitor number 4, the index is the competitor number, not just a position in a queue.

Using a Char as the Index

An index isn't limited to whole numbers — any ordinal type can be used, including Char. This is handy whenever the letter itself is what you want to look values up by, e.g. tallying how many learners scored each grade symbol (A to F) in a test:

Delphi — a Char-indexed array
var
  arrSymbolCount : array ['A'..'F'] of Integer;
  cGrade : Char;
begin
  cGrade := 'A';
  while cGrade <= 'F' do
  begin
    arrSymbolCount[cGrade] := 0;   // reset every element to zero first
    cGrade := succ(cGrade);         // moves 'A' to 'B', 'B' to 'C', and so on
  end;

  // later, whenever a learner's symbol is worked out:
  Inc(arrSymbolCount[cLearnerSymbol]);
succ and pred

succ(cGrade) gives the character that comes after cGrade in the alphabet; pred(cGrade) gives the one before it. They work like +1/-1 for any ordinal type, including Char, where plain arithmetic isn't allowed.

Matching a RadioGroup's ItemIndex to an Array

A RadioGroup's ItemIndex always starts counting from 0 for its first button — but an array you declare yourself might start at 1. When you use ItemIndex to pick an element to update (for example, tallying votes for a menu option), you need to decide which convention your array follows and stay consistent:

Array declared [0..4]Array declared [1..5]
iChoice := rgpMenu.ItemIndex;
Inc(arrVotes[iChoice]);
iChoice := rgpMenu.ItemIndex + 1;
Inc(arrVotes[iChoice]);

With the [1..5] version, the array index is always one more than ItemIndex, because ItemIndex itself never moves off its 0-based counting — only your array's lower bound changes.

IndexOutOfBounds / range check error

Delphi will happily compile arrNames[50] even if arrNames was declared as [1..30] — the mistake only surfaces while the program is running, as a range-check/IndexOutOfBounds error the moment that line executes. Whenever an index comes from user input or from a component like ItemIndex, validate it against the array's real bounds before using it.

Frequency Arrays — Counting With Ord

Every character has a numeric code. Ord(c) gives the code of a character and Chr(n) turns a code back into a character. A few codes worth knowing:

CharacterCode
' ' (space)32
'0' to '9'48 to 57
'A' to 'Z'65 to 90
'a' to 'z'97 to 122

Because the code is a whole number, it can be used directly as an index. A frequency array keeps one counter per possible character, and the character's code decides which counter to add to. No searching is needed — the character takes you straight to its own counter.

Delphi — count every ASCII character in a text
var
  arrFreq : array [0..127] of Integer;
  sText   : string;
  i       : Integer;
begin
  sText := 'Mzansi';
  for i := 0 to 127 do
    arrFreq[i] := 0;                         // every counter starts at zero
  for i := 1 to Length(sText) do
    Inc(arrFreq[Ord(sText[i])]);            // the code picks the counter

  for i := 0 to 127 do
    if arrFreq[i] > 0 then
      memOut.Lines.Add(Chr(i) + ': ' + IntToStr(arrFreq[i]));
end;
TRAP: assume plain ASCII text

The array above only has room for codes 0 to 127. A character with a bigger code (for example some accented letters) would index outside the array and cause a range error. This pattern is meant for plain English text.

Letters Only: Ord(c) − Ord('A')

If you only care about the 26 letters, a 0..127 array wastes space. Convert to capitals first, then subtract the code of 'A' so that A becomes index 0, B becomes 1, and Z becomes 25. To display, reverse the calculation with Chr(Ord('A') + i).

Delphi — letter frequencies (A to Z only)
var
  arrLetters : array [0..25] of Integer;
  sText : string;
  cCh   : Char;
  i     : Integer;
begin
  sText := UpperCase('Springbok rugby');
  for i := 0 to 25 do
    arrLetters[i] := 0;
  for i := 1 to Length(sText) do
  begin
    cCh := sText[i];
    if cCh IN ['A'..'Z'] then                  // ignore spaces and symbols
      Inc(arrLetters[Ord(cCh) - Ord('A')]);
  end;
  for i := 0 to 25 do
    if arrLetters[i] > 0 then
      memOut.Lines.Add(Chr(Ord('A') + i) + ' = ' + IntToStr(arrLetters[i]));
end;

Anagram Check (Balance Array)

Two words are anagrams when they use exactly the same letters the same number of times (ALERT and ALTER). Use one 26-slot array as a balance sheet: add 1 for every letter of the first word, subtract 1 for every letter of the second. If the words are anagrams, every slot ends on 0. Assume both words are already in capitals with no spaces.

Delphi — anagram test
var
  arrBalance : array [0..25] of Integer;
  sOne, sTwo : string;
  i : Integer;
  bAnagram : Boolean;
begin
  sOne := 'ALERT';
  sTwo := 'ALTER';
  for i := 0 to 25 do
    arrBalance[i] := 0;
  for i := 1 to Length(sOne) do
    Inc(arrBalance[Ord(sOne[i]) - Ord('A')]);
  for i := 1 to Length(sTwo) do
    Dec(arrBalance[Ord(sTwo[i]) - Ord('A')]);

  bAnagram := True;
  for i := 0 to 25 do
    if arrBalance[i] <> 0 then
      bAnagram := False;
end;

Pangram Check (Seen Array)

A pangram is a sentence that contains every letter of the alphabet at least once. Use a Boolean array with one slot per letter, all starting at False. Every time you meet a letter, switch its slot to True. Repeating a letter does not help you fill in a missing one, so the sentence is a pangram only if all 26 slots end up True.

Delphi — pangram test
var
  arrSeen : array [0..25] of Boolean;
  sLine : string;
  cCh : Char;
  i : Integer;
  bPangram : Boolean;
begin
  sLine := 'Pack my box with five dozen liquor jugs.';
  for i := 0 to 25 do
    arrSeen[i] := False;
  for i := 1 to Length(sLine) do
  begin
    cCh := UpCase(sLine[i]);
    if cCh IN ['A'..'Z'] then
      arrSeen[Ord(cCh) - Ord('A')] := True;
  end;

  bPangram := True;
  for i := 0 to 25 do
    if not arrSeen[i] then
      bPangram := False;
end;
Same idea, three jobs

Counting letters, comparing two words and checking for a full alphabet all use the same trick: Ord(letter) - Ord('A') turns a letter into an array index. None of these need sorted data.

Linear Search

Delphi
bFound := False;
for i := 1 to Length(arrNames) do
  if arrNames[i] = sSearch then
  begin
    ShowMessage('Found at position ' + IntToStr(i));
    bFound := True;
    Break;
  end;
if not bFound then
  ShowMessage('Not found');
Pick the right search for the job

The code above stops the loop with Break as soon as one match turns up — correct when you only expect a single match (e.g. one learner's ID number). If instead you needed every occurrence (e.g. every learner who chose "Physics"), you would drop the flag and Break, and simply let the loop run to the end, adding each match found along the way. Once the array is sorted, binary search (below) beats both approaches for speed.

Linear Search Without a Flag (Position 0 = Not Found)

You can also do a search without a Boolean variable at all. Array positions start at 1, so 0 can never be a real position. That makes 0 a perfect way to say "nothing found yet". Set the answer to 0, and only save a position if the answer is still 0 — this keeps the first match even though the loop runs to the end.

Delphi — linear search using position 0 as "not found"
iPos := 0;
for i := 1 to iCount do
  if (arrNames[i] = sSearch) and (iPos = 0) then
    iPos := i;

if iPos > 0 then
  ShowMessage(sSearch + ' is at position ' + IntToStr(iPos))
else
  ShowMessage('Not found');

Neither linear search version needs the array to be sorted.

Binary Search (sorted array)

Binary search is much faster than linear — it halves the search range each step. The array must be sorted first. We are searching for 23 in the array [2, 5, 8, 12, 16, 23, 38, 56, 72, 91].

Binary Search — searching for 23 idx: [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] val: 2 5 8 12 16 23 38 56 72 91 Step iLow iHigh iMid arrNums[iMid] 1 1 10 5 (1+10) div 2 16 < 23 → iLow = 6 2 6 10 8 (6+10) div 2 56 > 23 → iHigh = 7 3 6 7 6 (6+7) div 2 23 = 23 → FOUND! Found 23 at position 6 in just 3 steps! Linear search would have taken 6 steps. iLow := 1; iHigh := Length(arrNums); bFound := False; while (iLow <= iHigh) and not bFound do begin iMid := (iLow + iHigh) div 2; if arrNums[iMid] = iTarget then bFound := True
Delphi — binary search
iLow := 1;
iHigh := Length(arrNums);
bFound := False;
while (iLow <= iHigh) and not bFound do
begin
  iMid := (iLow + iHigh) div 2;
  if arrNums[iMid] = iTarget then
    bFound := True
  else if arrNums[iMid] < iTarget then
    iLow := iMid + 1
  else
    iHigh := iMid - 1;
end;
if bFound then
  ShowMessage('Found at position ' + IntToStr(iMid));

How String Comparison Works

Sorting a string array with > and < only makes sense once you know what Delphi is actually comparing. It never looks at "the alphabet" directly — it walks each string letter by letter and compares the underlying ASCII value of each character, stopping at the first pair of letters that differ.

ComparisonResultWhy
'Alice' = 'alice'False'A' is ASCII 65, 'a' is ASCII 97 — string comparison is case-sensitive.
'Bob' < 'Eve'TrueFirst letters differ straight away: 'B' (66) is less than 'E' (69).
'Farai' < 'Farm'TrueThe first three letters ('F','a','r') match, so the 4th letter decides: 'a' (97) is less than 'm' (109).
'Gio' > 'Gi'TrueDelphi pads the shorter string with trailing spaces to compare them — so 'Gi' becomes 'Gi ', and 'o' (111) beats a space (32).
Capitals sort before lowercase

Because every uppercase letter has a lower ASCII value than every lowercase letter, an unsorted mix of cases will group all the capitalised words before any lowercase word once sorted — not what most people expect from "alphabetical order". If that matters, convert both sides to the same case (e.g. with UpperCase()) before comparing or sorting.

Bubble Sort — Pass by Pass

Bubble sort compares adjacent elements and swaps them if they are in the wrong order. After each full pass, the largest unsorted value "bubbles" to its correct position at the end. Array: [5, 3, 8, 1, 9] — sorting ascending.

Bubble Sort — [5, 3, 8, 1, 9] Start Pass 1 Pass 2 Pass 3 Pass 4 Sorted 5 3 8 1 9 3 5 1 8 9 9 locked in 3 1 5 8 9 8, 9 locked 1 3 5 8 9 1 3 5 8 9 1 3 5 8 9 violet = swapped this pass green = locked in final position
Delphi — Bubble Sort
for i := Length(arrNums) - 1 downto 1 do
  for j := 1 to i do
    if arrNums[j] > arrNums[j + 1] then
    begin
      iTemp := arrNums[j];
      arrNums[j] := arrNums[j + 1];
      arrNums[j + 1] := iTemp;
    end;
Stop early once nothing swaps

The version above always completes every single pass, even once the array is already sorted. A smarter bubble sort keeps a Boolean flag and quits the moment a whole pass goes by with no swaps at all — because that can only happen when the array is fully sorted:

Delphi — Bubble Sort that quits early
iEndCounter := Length(arrNums) - 1;
repeat
  bSwapped := False;
  for j := 1 to iEndCounter do
    if arrNums[j] > arrNums[j + 1] then
    begin
      iTemp := arrNums[j];
      arrNums[j] := arrNums[j + 1];
      arrNums[j + 1] := iTemp;
      bSwapped := True;
    end;
  Dec(iEndCounter);            // the tail end is sorted, so search one less item next time
until not bSwapped;         // no swaps this pass = fully sorted, stop looping

Selection Sort — Pass by Pass

Selection sort finds the smallest remaining element and swaps it into its correct position. Same array: [5, 3, 8, 1, 9].

Selection Sort — [5, 3, 8, 1, 9] Start Pass 1 Pass 2 Pass 3 Pass 4 5 3 8 1 9 1 3 8 5 9 min=1 found at [4], swap → [1] locked 1 3 8 5 9 min=3 already at [2] — locked 1 3 5 8 9 min=5 found at [4], swap → [3] locked 1 3 5 8 9 SORTED!
Delphi — Selection Sort
for i := 1 to Length(arrNums) - 1 do
begin
  iMin := i;
  for j := i + 1 to Length(arrNums) do
    if arrNums[j] < arrNums[iMin] then
      iMin := j;
  if iMin <> i then
  begin
    iTemp := arrNums[i];
    arrNums[i] := arrNums[iMin];
    arrNums[iMin] := iTemp;
  end;
end;

Parallel Arrays

Two arrays are parallel when the same index refers to the same "record" — e.g. arrNames[3] and arrMarks[3] both belong to the same student. When you sort one, you must sort both to keep them in sync.

ANALOGY — your things move with you

At a table, each person has their own cup, plate and bowl — three parallel dinner sets, where place setting [3] in each belongs to the same person. If that person moves to a different seat, they take all three of their things with them — you never leave their cup behind while their plate moves.

Sorting parallel arrays works exactly the same way: whenever the sort swaps two items in arrNames, you must swap the same two indexes in arrMarks (and every other parallel array) — so each student keeps their own name and their own mark together.

Parallel Arrays — Same Index, Different Data arrNames 'Alice' 'Bob' 'Callie' 'David' 'Eve' [1] [2] [3] [4] [5] arrMarks 78 65 91 54 88 arrNames[3] = 'Callie' linked to arrMarks[3] = 91 — same student, same index
Delphi — parallel sort (names & marks together)
for i := 1 to Length(arrNames) - 1 do
  for j := i + 1 to Length(arrNames) do
    if arrNames[i] > arrNames[j] then
    begin
      // Swap both arrays at the same time
      sTemp := arrNames[i]; arrNames[i] := arrNames[j]; arrNames[j] := sTemp;
      iTemp := arrMarks[i]; arrMarks[i] := arrMarks[j]; arrMarks[j] := iTemp;
    end;

Inserting, Deleting, Removing Duplicates and Merging

An array of fixed size cannot really "grow" or "shrink", so these algorithms work with a count variable (iCount) that says how many slots are actually in use. The array is declared bigger than you need (for example array[1..Max]), and everything after position iCount is simply ignored. Always loop to iCount, never to Max.

Insert an Element at a Position

To squeeze a value into the middle, you first have to make a gap. Shift the elements to the right, starting from the end. If you started at the front you would copy the same value over and over and destroy the data.

  1. Make sure there is spare room (iCount < Max).
  2. Loop from iCount down to the insert position, copying each element one place to the right.
  3. Put the new value in the gap.
  4. Increase the count with Inc(iCount).
Delphi — insert 70 at position 3 of [45, 62, 78, 90]
if iCount < Max then
begin
  for i := iCount downto iPlace do
    arrScores[i + 1] := arrScores[i];    // shift right, last element first
  arrScores[iPlace] := iNew;                // drop the new value into the gap
  Inc(iCount);
end;
// with iPlace = 3 and iNew = 70 the used part is now [45, 62, 70, 78, 90]

Delete an Element

Deleting works in the opposite direction. Shift everything after the deleted position one place to the left, starting from the front, so the next value overwrites the one you are removing. Then reduce the count.

Delphi — delete position 2 of [45, 62, 70, 78, 90]
for i := iPlace to iCount - 1 do
  arrScores[i] := arrScores[i + 1];      // shift left, first element first
Dec(iCount);
// with iPlace = 2 the used part is now [45, 70, 78, 90]
TRAP: shift in the right direction

Insert shifts right, from the end (downto). Delete shifts left, from the front (to). Mixing the directions overwrites values you still need. Also remember the count: forgetting Inc(iCount) or Dec(iCount) means your later loops will miss the new value or show a leftover one.

Remove Duplicates Into a Second Array

Instead of deleting from the original, build a second array that only receives a value if it is not already in there. For each value in the original, search the new array. If it was not found, append it.

Delphi — ['N2','R300','N2','M5','R300'] becomes ['N2','R300','M5']
iNewCount := 0;
for i := 1 to iCount do
begin
  bDuplicate := False;
  for j := 1 to iNewCount do
    if arrNew[j] = arrRoutes[i] then
      bDuplicate := True;
  if not bDuplicate then
  begin
    Inc(iNewCount);
    arrNew[iNewCount] := arrRoutes[i];
  end;
end;

The first occurrence of each value is kept, and the original order is preserved. Make sure arrNew is declared big enough to hold as many values as the original. The data does not need to be sorted.

Merge Two Arrays (Concatenate)

Joining two arrays end to end is simple: copy the first one into the result, then copy the second one starting just after it. The result is not sorted — it is just list A followed by list B.

Delphi — concatenate arrA and arrB into arrC
for i := 1 to iCountA do
  arrC[i] := arrA[i];
for i := 1 to iCountB do
  arrC[iCountA + i] := arrB[i];
iCountC := iCountA + iCountB;

Merge Two Sorted Arrays (Result Stays Sorted)

If both arrays are already sorted ascending, you can merge them into one sorted array without sorting again. Keep one position marker per input array (i for A, j for B) and one for the result (k). Compare the two values the markers point at, copy the smaller one and move only that marker forward. When one array runs out, copy whatever is left of the other.

StepA[i]B[j]Copied to result
1343 (A is smaller)
2844
3898
41599
5152015 — A is now finished
left over–20, 2520, 25
Delphi — merge sorted [3, 8, 15] and [4, 9, 20, 25]
i := 1;  j := 1;  k := 0;
while (i <= iCountA) and (j <= iCountB) do
begin
  Inc(k);
  if arrA[i] <= arrB[j] then
  begin
    arrC[k] := arrA[i];
    Inc(i);
  end
  else
  begin
    arrC[k] := arrB[j];
    Inc(j);
  end;
end;

// only one of these two loops will actually run
while i <= iCountA do
begin
  Inc(k);
  arrC[k] := arrA[i];
  Inc(i);
end;
while j <= iCountB do
begin
  Inc(k);
  arrC[k] := arrB[j];
  Inc(j);
end;
// arrC = [3, 4, 8, 9, 15, 20, 25]
Which of these need sorted data?
AlgorithmNeeds sorted data?
Linear search (with or without a flag)No
Binary searchYes
Insert at a given position, delete at a given positionNo (insert at the correct position to keep an already-sorted array sorted)
Remove duplicates (second array method)No
Concatenate two arraysNo (and the result is not sorted)
Merge two sorted arraysYes — both inputs must be sorted the same way
Frequency, anagram and pangram arraysNo

Date Methods (Grade 11)

Delphi has built-in functions for working with dates — required for Grade 11 Term 1.

Add this to your uses clause

IsLeapYear, YearOf, MonthOf and DayOf live in the DateUtils unit. Add uses DateUtils; near the top of your unit, or Delphi will report "undeclared identifier" when you try to use them.

FunctionReturnsExample & Output
NowCurrent date & time (TDateTime)lblDate.Caption := DateToStr(Now) → '2025/05/30'
DateToStr(d)Date as formatted stringDateToStr(dtpBirth.Date) → '2008/03/15'
TimeToStr(t)Time as formatted stringTimeToStr(Now) → '14:32:07'
StrToDate(s)String → TDateTimeStrToDate('2024/05/01')
IsLeapYear(y)Boolean (True/False)IsLeapYear(2024) → True
YearOf(d)Integer yearYearOf(dtpDate.Date) → 2025
MonthOf(d)Integer month (1–12)MonthOf(Now) → 5
DayOf(d)Integer day (1–31)DayOf(Now) → 30
Delphi — Date examples with output
// Display today's date
lblToday.Caption := DateToStr(Now);         // '2025/05/30'

// Calculate age in years
iAge := YearOf(Now) - YearOf(dtpBirth.Date); // e.g. 17

// Check leap year
if IsLeapYear(YearOf(Now)) then
  ShowMessage('This is a leap year')
else
  ShowMessage('Not a leap year');

The Leap Year Rule Done By Hand

Sometimes you are asked to work without IsLeapYear. A year is a leap year when it is divisible by 400, or it is divisible by 4 but not by 100. So 2024 and 2000 are leap years; 1900 and 2026 are not.

Delphi — leap year without IsLeapYear
bLeap := (iYear mod 400 = 0) or
         ((iYear mod 4 = 0) and (iYear mod 100 <> 0));

Age From a Birth Date

Subtracting the two years, as in the quick example above, is only approximately right. It gives the age the person will be some time this year. If the birthday has not happened yet this year, the real age is one less. A birthday has not been reached when today's month is before the birth month, or the months are equal but today's day is before the birth day.

Delphi — exact age in years
iAge := YearOf(dtToday) - YearOf(dtBorn);
if (MonthOf(dtToday) < MonthOf(dtBorn)) or
   ((MonthOf(dtToday) = MonthOf(dtBorn)) and (DayOf(dtToday) < DayOf(dtBorn))) then
  Dec(iAge);                  // birthday still to come this year
// born 12 Aug 2008, today 3 May 2026:  2026 - 2008 = 18, birthday not reached, so 17

Days Between Two Dates Without Date-Difference Routines

The idea: turn each date into a single day number (how many days have passed since the start of year 1), then subtract. The earlier date gives the smaller number, so later minus earlier is the number of elapsed days. To build a day number:

  1. Take the number of completed years: iYear - 1. Each one has 365 days.
  2. Add one extra day for every leap year in that stretch: DIV 4, then subtract the century years that are not leap years (DIV 100), then add back those divisible by 400 (DIV 400).
  3. Add the days of every completed month this year, using a table of month lengths (February = 28).
  4. If this year is a leap year and the date is after February, add 1 more day.
  5. Add the day of the month.
Delphi — a day-number function and the difference
function DayNumber(iYear, iMonth, iDay: Integer): Integer;
const
  arrMonthLen : array [1..12] of Integer =
    (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var
  iDone, m : Integer;
  bLeap : Boolean;
begin
  iDone  := iYear - 1;                                       // completed years
  Result := iDone * 365 + iDone div 4 - iDone div 100 + iDone div 400;
  bLeap  := (iYear mod 400 = 0) or
            ((iYear mod 4 = 0) and (iYear mod 100 <> 0));
  for m := 1 to iMonth - 1 do
    Result := Result + arrMonthLen[m];                 // completed months
  if bLeap and (iMonth > 2) then
    Inc(Result);                                       // 29 Feb has already happened
  Result := Result + iDay;
end;

// 25 Feb 2024 to 2 March 2024
iDays := DayNumber(2024, 3, 2) - DayNumber(2024, 2, 25);   // 738947 - 738941 = 6
Elapsed days, not inclusive days

Subtracting the two day numbers counts the days between the dates, so the starting day itself is not counted. If a question wants both the first and last day included, add 1. Check the working with 2024: 25 Feb to 29 Feb is 4 days, then 1 Mar and 2 Mar bring it to 6, because 2024 is a leap year.

Before a binary search will work, the array must be:

Binary search repeatedly halves the list, which only works if it is sorted first.

When you sort one of two parallel arrays, you must:

Parallel arrays share an index, so every swap must be applied to both to keep records together.

A bubble sort works by repeatedly comparing:

Bubble sort compares neighbouring (adjacent) elements and swaps them if out of order.