Ms Coetzee · Information Technology
10

Grade 10 Practical Study Reference

A printable guide to the practical Delphi programming for Grade 10 (Paper 1 skills), with the year planner and exam extras.

Practical  •  Term Planner  •  Exam Extras
CAPS-aligned · Printable booklet edition

Contents — Grade 10 Practical

Grade 10 · Practical

Algorithms & Problem Solving Grade 10

Before writing a single line of code, good programmers plan their solution. This page covers algorithms, pseudocode, flowcharts, IPO tables and trace tables — the thinking tools of programming.

T1Term 1 · Algorithms, Pseudocode & Problem Solving

What is an Algorithm?

Imagine you want to make a cup of tea. You don't just randomly pour hot water and hope for the best — you follow steps: boil water, put teabag in cup, pour water, wait, add milk. That ordered list of steps is an algorithm.

In computing, an algorithm is a precise, step-by-step set of instructions used to solve a problem or complete a task. Every program you write starts as an algorithm in your head (or on paper) before it becomes code.

TIP

Think of an algorithm like a recipe. A recipe tells you exactly what ingredients to use, in what order, and what to do with them. A computer program is just a recipe written in a language the computer understands.

Key Characteristics of a Good Algorithm

PropertyMeaningExample of failure
ClearEvery step is unambiguous — only one interpretation"Do something with the number" — too vague
FiniteIt must end after a certain number of stepsA loop that never stops
CorrectIt must produce the right answer every timeAdding instead of multiplying
OrderedSteps must follow a logical sequenceCalculating average before calculating total
EfficientNo unnecessary steps or wasted resourcesCalculating the same total three times

Why Do Algorithms Matter?

Before writing code, planning with an algorithm helps you:

REAL WORLD

In 1999, NASA's Mars Climate Orbiter crashed because one team used metric units and another used imperial in their calculations. A clear algorithm with defined units would have caught this. The mistake cost $327 million. Accurate algorithms matter.

The Problem-Solving Cycle

  1. Understand the problem — State it in your own words. What is given? What must be produced?
  2. Plan the solution — Write pseudocode or draw a flowchart. Use an IPO table.
  3. Implement — Convert your plan into Delphi code.
  4. Test — Run the program and check output against expected results using a trace table.
  5. Fix errors — Debug and correct any mistakes, then retest.

IPO Tables (Input – Process – Output)

An IPO table is the first planning tool you use. It forces you to identify three things before writing any code: what data goes in, what happens to it (process), and what comes out.

InputProcessOutput
Length, Width Area = Length × Width
Perimeter = 2 × (Length + Width)
Area, Perimeter of rectangle
Mark1, Mark2, Mark3 Total = Mark1 + Mark2 + Mark3
Average = Total ÷ 3
Total marks, Average mark
A number (num) IF num MOD 2 = 0 THEN "Even" ELSE "Odd" "Even" or "Odd"
Temperature in Celsius (C) F = (C × 9/5) + 32 Temperature in Fahrenheit (F)
EXAM TIP

In exams you may be asked to complete an IPO table. Always write the Process column as a formula or decision — not just "calculate it". Show your working: Area = Length × Width, not just "work out the area".

TOE Charts (Task – Object – Event)

Once a program has several buttons and several jobs to do, an IPO table stops being enough on its own — it never says which component is responsible for a job, or what has to happen before that component springs into action. A TOE chart closes that gap: for every task the program must carry out, it records the object (component) that will handle it and the event that sets that component's code running.

Building a TOE Chart
  1. List out everything the program needs to do
  2. Match each item on that list to the component that will handle it
  3. Decide which event on that component should trigger the code

Worked Example: Tuck Shop Cooldrink Stand

A cooldrink at the school tuck shop costs R12. A learner types in how many cooldrinks they want, clicks a button to see the total, types in the money they handed over, then clicks a second button to see their change. Breaking that down task by task produces the following TOE chart:

TaskObjectEvent
Read how many cooldrinks were orderedsedQtyExit
Work out the total costbtnTotalClick
Show the total on the receiptbtnTotal, memReceiptClick, None
Read how much money was handed overbtnChange, edtPaidClick, None
Work out the change owedbtnChangeClick
Show the change on the receiptbtnChange, memReceiptClick, None
Some Objects Never Trigger Anything

Notice that "Show the total on the receipt" lists two objects. Clicking btnTotal is what actually makes the display happen — memReceipt is only there to show the result, and has no event of its own. Whenever an object is just along for the ride like this, write None next to it in the Event column.

Once the chart is finished, coding becomes close to mechanical: open one event handler for every distinct event you listed, and turn that row's task into a line or two of Delphi inside it.

Flowcharts

A flowchart shows the steps of an algorithm as a picture using standard symbols connected by arrows. It is easier to spot errors in a diagram than in written text, which is why flowcharts are so useful.

Flowchart Symbol Reference

Flowchart Symbols Start / End Oval Marks the start or end of a program Input / Output Parallelogram Read input from user or display a result Process Rectangle A calculation or assignment step Decision Yes / No Diamond A question with two possible paths (Yes/No) Arrows show direction of flow
BEGIN INPUT colour Is colour blue? Yes Show "colour is blue" END No Show "colour is NOT blue" END

Flowchart example: checking if a colour is blue

Worked Example: Is a Number Even or Odd?

This flowchart takes a number as input, checks if it divides evenly by 2, and displays "Even" or "Odd" before ending.

START INPUT num num MOD 2 = 0 ? YES NO OUTPUT "Even" OUTPUT "Odd" END

Worked Example: Nested Decisions

Here one decision sits inside another. First we check the age; only if that is True do we ask the second question about the licence.

START Age >= 18 ? False True bHasLicence = True ? False bDrive := False True bDrive := True END

Flowchart: nested decisions — check age first; only if True check the licence.

TIP

The diamond shape always asks a Yes/No question. The two arrows leaving the diamond are labelled YES and NO. Both paths must eventually reach the END oval.

Pseudocode

Pseudocode is fake code written in plain English that describes the logic of a program. It is not real Delphi code — it is for planning only. Anyone who understands programming should be able to read your pseudocode, even if they don't know Delphi.

Pseudocode Rules

Pseudocode – Basic Statements
SET total TO 10          // assignment
INPUT age                // get data from user
OUTPUT total             // show result
SET area TO length * width   // calculation

IF age >= 18 THEN
    OUTPUT "May vote"
ELSE
    OUTPUT "Too young to vote"
ENDIF

Example: Find the Average of Three Marks

Pseudocode
START
    INPUT mark1
    INPUT mark2
    INPUT mark3
    SET total TO mark1 + mark2 + mark3
    SET average TO total / 3
    OUTPUT "Total: ", total
    OUTPUT "Average: ", average
END

Example: Even or Odd

Pseudocode
START
    INPUT num
    IF num MOD 2 = 0 THEN
        OUTPUT num, " is Even"
    ELSE
        OUTPUT num, " is Odd"
    ENDIF
END

Trace Tables

A trace table is used to test an algorithm by hand. You pick a test value, then track every variable as you step through the algorithm line by line. This helps you check whether the algorithm produces the correct output.

Trace Table Example: Even or Odd (num = 7)

StepInstructionnumnum MOD 2Output
1START———
2INPUT num7——
3IF num MOD 2 = 0?71—
4Condition FALSE → ELSE branch71—
5OUTPUT "Odd"71"Odd"
6END———

Trace Table Example: Average of Three Marks (90, 70, 80)

StepInstructionmark1mark2mark3totalaverage
1INPUT mark190————
2INPUT mark29070———
3INPUT mark3907080——
4total = mark1+mark2+mark3907080240—
5average = total / 390708024080
6OUTPUT total, average———24080

Comparing Algorithms

When two algorithms solve the same problem, we compare them. Three key criteria matter in CAPS exams:

CriterionWhat it meansPoor exampleBetter example
Sequence Steps must be in the correct order Calculate average BEFORE total Calculate total first, THEN average
Precision Each step must have one clear meaning "Calculate the answer" SET total TO mark1 + mark2 + mark3
Efficiency No unnecessary steps or repeated work Calculate total three separate times Calculate total once and reuse the variable

Common Algorithm Patterns in Delphi

Finding Smallest and Largest Values

The trick: assume the first value is both smallest and largest, then compare the rest one by one.

Delphi
var
  iNum1, iNum2, iNum3: Integer;
  iSmallest, iLargest: Integer;
begin
  iNum1 := StrToInt(edtNum1.Text);
  iNum2 := StrToInt(edtNum2.Text);
  iNum3 := StrToInt(edtNum3.Text);

  iSmallest := iNum1;   // assume first is smallest
  iLargest  := iNum1;   // assume first is largest

  if iNum2 < iSmallest then iSmallest := iNum2;
  if iNum3 < iSmallest then iSmallest := iNum3;
  if iNum2 > iLargest  then iLargest  := iNum2;
  if iNum3 > iLargest  then iLargest  := iNum3;

  lblResult.Caption := 'Smallest: ' + IntToStr(iSmallest)
                     + ' Largest: ' + IntToStr(iLargest);
end;

Swapping Two Values

IMPORTANT RULE

You always need a temporary variable to swap values. Without it, one value gets overwritten before it can be saved — like trying to swap two glasses of water without a third empty glass.

Delphi
var
  iA, iB, iTemp: Integer;
begin
  iA := StrToInt(edtA.Text);
  iB := StrToInt(edtB.Text);

  iTemp := iA;    // step 1: save A into temp
  iA    := iB;    // step 2: overwrite A with B
  iB    := iTemp; // step 3: put saved A into B

  edtA.Text := IntToStr(iA);
  edtB.Text := IntToStr(iB);
end;

Even or Odd

Delphi
var
  iNum: Integer;
begin
  iNum := StrToInt(edtNum.Text);
  if iNum MOD 2 = 0 then
    lblResult.Caption := 'Even number'
  else
    lblResult.Caption := 'Odd number';
end;

Factor Check

A number is a factor if it divides another with no remainder (MOD = 0). For example, 3 is a factor of 12 because 12 ÷ 3 = 4 with remainder 0.

Delphi
if iNum2 MOD iNum1 = 0 then
  lblResult.Caption := IntToStr(iNum1) + ' is a factor of ' + IntToStr(iNum2)
else
  lblResult.Caption := IntToStr(iNum1) + ' is NOT a factor of ' + IntToStr(iNum2);
Grade 10 · Practical

Introduction to Delphi Grade 10

Delphi is a visual programming environment — you design the screen AND write the code. You drag components onto a form to build the interface, then write Delphi code to make it all work. This page covers the IDE layout, components, naming, events, and your first program.

T1Term 1 · Introduction to the Delphi IDE

The Delphi IDE — What You See When You Open It

When you open Delphi, this is what you will see. It might look overwhelming at first — but each area has one clear job:

Delphi 11 IDE in Design View
Delphi 11 — Design View (this is where you build the form your user will see)
Object Inspector
Object Inspector — set properties like Name, Caption, Color
Tool Palette
Tool Palette — drag components from here onto the form

Switching to Code View

Press F12 to toggle between the Design View (what you see above) and the Code View (where you type your Delphi code).

Delphi Code View
Code View — this is the Delphi code structure that is automatically created for you

The Delphi IDE Layout

An Integrated Development Environment (IDE) is a software application that combines the tools a programmer needs — a code editor, a compiler, and a debugger — into a single interface, so you can design, write, test and run a program without switching between separate tools.

Think of it this way

Think of the IDE as your workshop — every tool you need (editor, compiler, debugger) is laid out and ready to use, all in one place.

Why Delphi Counts as "RAD" Software

RAD stands for Rapid Application Development. The label applies to Delphi because most of the visual work is already done for you: instead of writing code to draw a button or a text box pixel by pixel, you drag a ready-made component from the Tool Palette onto the form. Skipping that low-level drawing work is what lets a small classroom project turn into a working app within a single lesson.

Delphi IDE MENU BAR File Edit View Project Run Component Tools Help STRUCTURE PANEL Form1 btnCalculate lblResult edtInput memOutput imgLogo FORM / DESIGN AREA Form1 TLabel — lblTitle TEdit — edtInput TButton TMemo — memOutput Press F12 to toggle Code View TOOL PALETTE Standard TLabel TButton TEdit Additional TMemo TImage TPanel Win32 TDateTimePicker Dialogs TOpenDialog OBJECT INSPECTOR btnCalculate : TButton Caption'Calculate' NamebtnCalculate EnabledTrue Font.Size10 Properties | Events CODE VIEW F12 1procedure TForm1.btnCalculateClick(Sender: TObject); 2begin 3 ShowMessage('Hello!'); 4end; ← Write your code between begin and end

Key IDE Panels

PanelPurpose
Menu BarTop menu — File, Edit, View, Project, Run, Tools etc.
Tool PaletteAll Delphi components grouped by category. Click a component, then click on the form to place it.
Object InspectorSets the initial properties and events of a selected component.
Structure Panel (Object TreeView)Quick reference showing all objects on the current form, displayed in a hierarchical (tree) view.
Form / Design AreaThe visual canvas — drag and drop components here to build the UI.
Code ViewWhere you write Delphi code. Toggle with F12.

Objects, Classes & Components

Delphi is an Object-Oriented Programming (OOP) language, so almost everything you place on a form is an object. To talk about objects precisely, three related terms are used:

TermMeaning
ClassThe plan or blueprint for an object — for example TButton is the class that defines what every button can look like and do. Class names always start with a capital T.
ObjectAn instance of a class — an actual button, label or form that exists in your program, e.g. btnCalculate is an object (instantiation) of the class TButton.
ComponentA particular type of object that can be placed on a form to build a user-friendly, interactive interface (e.g. a Button, Label or Edit).
Blueprint analogy

Before a house is built, an architect draws up plans — the class. Many houses can then be built from the same plan — each one is an object (an instantiation of the class). TButton is the plan; btnCalculate and btnCancel are two different objects built from that same plan.

Every object has:

Basic Format of Statements

An assignment statement stores a value in a property or variable using the assignment operator :=. We use code in Delphi to assign values to properties of components in the following format:

Delphi — general format
Component.Property := Value;

All the properties a component has can be seen in the Object Inspector when that component is selected — the same properties you set visually at design time can also be set in code.

Two rules every statement follows
  • Always assign TO the component/property on the left side of := — never the other way round.
  • Every statement ends with a semicolon ;
Delphi — examples
Form1.Height := 500;
Form1.Width := 700;
Button1.Caption := 'Register';
Shape1.Top := 20;
Shape1.Left := 20;

Step-by-Step: Creating Your First Project

  1. File → New → Windows VCL Application — creates a blank Form (TForm).
  2. Place components by clicking them in the Tool Palette, then clicking on the form.
  3. Set properties in the Object Inspector (e.g. change a button's Caption).
  4. Double-click a button to go to Code View and write the event handler.
  5. File → Save All (Ctrl+Shift+S) — save in a NEW dedicated folder.
  6. Press F9 to compile and run.
Save in its own folder — always!

Each project must be saved in its own dedicated folder. Save the Unit file as FileName_u.pas and the Project file as FileName_p.dpr. Never mix two projects in one folder.

The Files Delphi Creates

Delphi creates several files for every program, but you only ever need to save two of them yourself — Delphi regenerates the rest automatically when you run the program.

FileExtensionContainsSave it yourself?
Unit file.pasThe Delphi code you write (event handlers, class definition)Yes
Project file.dprInformation that ties the units of a project togetherYes
Form file.dfmThe visual layout of the form and its componentsNo — saved automatically with the Unit
Transferring a project to another computer

If you need to copy a project to another computer, copy the .dpr, .dfm and .pas files — Delphi will recreate every other file the next time you run the program.

Visual Component Reference

Components are the building blocks placed on a form. Each is an object with properties and events. Here is what the most common ones look like:

Form1 TForm The window itself Your Label Here TLabel Displays text Click Me TButton Triggers code user types here TEdit Single-line input Line 1 Line 2 Line 3 TMemo Multi-line text [ image ] TImage Displays a picture RadioGroup Option A Option B Option C TRadioGroup ✓ Accept terms Subscribe TCheckBox Panel1 Groups components TPanel scroll down ... TListBox List of items

Naming Convention

Every component gets a prefix that indicates its type, followed by a meaningful name. This makes code readable.

PrefixComponent TypeExample
btnTButtonbtnCalculate
lblTLabellblResult
edtTEditedtName
memTMemomemOutput
imgTImageimgLogo
pnlTPanelpnlHeader
sedTSpinEditsedNotes
cboTComboBoxcboGrade
lstTListBoxlstNames
rgpTRadioGrouprgpGender
chkTCheckBoxchkAgree
tmrTTimertmrClock

Accelerator (Hot) Keys

Placing an & in front of a letter in a component's Caption underlines that letter and turns it into a keyboard shortcut. Pressing Alt + that letter clicks the component without using the mouse.

Delphi — example
btnRed.Caption := '&Red';   // underlines the R — press Alt+R to click the button

Event-Driven Programming

Delphi programs are event-driven — code only runs when something HAPPENS (an event), like pressing a button, typing in a box, or a timer ticking.

Vending Machine Analogy

Think of a vending machine. It just sits there doing nothing — until you push a button. That press is the event. The machine then dispenses the item — that is the event handler (your code). If no button is pressed, nothing happens. Delphi works exactly like this.

EventWhen it firesCommon use
OnClickUser clicks a button / componentCalculate, submit, navigate
OnChangeText in an edit box changesLive validation, update display
OnKeyPressA key is pressed while component has focusAccept only numbers
OnCreateForm loads / opensInitialise variables, load data
OnTimerTimer interval elapsesCountdown, clock display

How to Create an Event Handler

  1. In Design View, double-click a button to create its OnClick handler automatically.
  2. For other events, go to the Events tab in the Object Inspector and double-click next to the event name.
  3. Delphi creates a skeleton procedure. Write your code between begin and end.
  4. Never change the procedure header — only add code inside.
Delphi — Button Click Event
procedure TForm1.btnCalculateClick(Sender: TObject);
begin
  // Your code goes here
  ShowMessage('Button clicked!');
end;

ShowMessage and InputBox

ShowMessage displays a pop-up with a message. InputBox pops up a window asking the user to type something. Both are modal — the program pauses until the user responds.

Information ✕ i Hello world! OK ShowMessage('Hello world!') One message, one OK button. No return value. Name ✕ Enter your name: Alice OK Cancel InputBox('Name','Enter your name:','') Always returns a String — convert if needed
Delphi — ShowMessage
ShowMessage('Hello world!');
ShowMessage('Result: ' + IntToStr(iAnswer));
Delphi — InputBox (returns String, convert as needed)
// Returns a string
sName   := InputBox('Name', 'Enter your name:', '');

// Convert to integer
iNum    := StrToInt(InputBox('Number', 'Enter a number:', ''));

// Convert to real
rAmount := StrToFloat(InputBox('Amount', 'Enter amount:', ''));

// Get first character only
cClass  := InputBox('Class', 'Enter class:', '')[1];

Components — Properties

Properties control how a component looks and behaves. Set them in the Object Inspector or through code.

PropertyDescriptionExample Value
NameUnique identifier used in codebtnCalculate
CaptionText shown on labels, buttons, forms'Calculate'
TextText in a TEdit boxedtName.Text
HeightComponent height in pixels30
WidthComponent width in pixels150
Font.SizeText size14
Font.ColorText colour (note: Color not Colour)clRed
VisibleWhether component is shownTrue / False

More Properties in Code

The same Component.Property := Value; format works for every property, including nested ones like Font.Color:

Delphi
Label1.Font.Color   := clGreen;
Shape1.Brush.Color  := clRed;

Methods

Methods are pre-written operations that perform tasks on components. Format: ComponentName.Method;

MethodEffect
Button1.Hide;Makes the button invisible
Button1.Show;Makes the button visible again
Edit1.SetFocus;Moves the cursor into the edit box
Memo1.Clear;Clears all text in the memo
Form1.Close;Closes the form / program
RichEdit1.Lines.Add('text');Adds a new line to a RichEdit or Memo

Syntax Rules

Syntax Errors

Forgetting the closing semicolon ; on a statement causes a syntax error. There is never a semicolon before else. Begin/end pairs must always match.

Grade 10 · Practical

Delphi Components & Events Grade 10

Beyond buttons and labels — these components are used in most IT practical exams. Know each one's key property and how to use it in code.

T2Term 2 · Core Components & Events

Input Components

ComponentKey Property/EventHow to use in code
TEdit.TextedtName.Text — read or write as string
TSpinEdit (sedNum).ValuesedNum.Value — returns Integer directly
TComboBox.Text or .ItemIndexcboMonth.Text or cboMonth.ItemIndex (0-based)
TListBox.ItemIndex, .ItemslstNames.Items.Add('Alice'); lstNames.ItemIndex
TRadioGroup.ItemIndexif rgpGender.ItemIndex = 0 then (0 = first item)
TCheckBox.Checkedif chkAgree.Checked then
TTrackBar.PositiontrkVolume.Position — Integer
TDateTimePicker.DatedtpBirth.Date — TDateTime value

Output Components

ComponentKey PropertyCode example
TLabel.CaptionlblResult.Caption := 'Done';
TMemo.LinesmemOut.Lines.Add('Hello');
TRichEdit.LinesSame as Memo; supports formatting
TListBox.ItemslstOut.Items.Add('Alice');
TImage.PictureimgPhoto.Picture.LoadFromFile('face.jpg');
TProgressBar.PositionpbrLoad.Position := 75;
TPanel.Caption, .ColorpnlInfo.Caption := 'Ready';

Bitmap Buttons (TBitBtn)

A TBitBtn is a special type of button that can show a caption and a small picture (bitmap) on its face, making an interface look more professional. Its most useful property is Kind — setting it gives the button pre-programmed behaviour, so some Bitmap Buttons need no code at all.

Kind valueBuilt-in behaviour
bkCloseCloses the form/program — fully pre-programmed
bkOKCloses a modal form and returns mrOk
bkCancelCloses a modal form and returns mrCancel
bkYes / bkNoCloses a modal form, returning mrYes / mrNo
bkHelpTriggers context help — the programmer adds the code
Naming

Bitmap Buttons use the prefix bmb, e.g. bmbClose.

ComboBox — Adding Items

Delphi
// At design time: use Items property in Object Inspector
// At runtime:
cboMonth.Items.Add('January');
cboMonth.Items.Add('February');
cboMonth.ItemIndex := 0;  // select first item

// Reading selected item
sSelected := cboMonth.Text;
iIndex    := cboMonth.ItemIndex;

ListBox — Adding, Clearing, Accessing Items

Delphi
lstNames.Items.Add('Alice');         // add item
lstNames.Items.Clear;                 // remove all
lstNames.Items.Delete(0);            // remove first item
iCount := lstNames.Items.Count;       // number of items
sItem  := lstNames.Items[2];         // access item at index 2
sSelected := lstNames.Items[lstNames.ItemIndex]; // selected item

Resetting a Selection — the -1 Trick

The ItemIndex property tells you which item is selected, counting from 0 (the first item). When nothing is selected, ItemIndex is -1.

This works in reverse too: setting ItemIndex := -1 deselects everything and visually clears the box. This is the standard way to reset a TComboBox, TListBox or TRadioGroup — for example when a user clicks a "Clear form" button.

Delphi — clearing selections
cboMonth.ItemIndex  := -1;   // ComboBox: no month selected (box appears empty)
rgpGender.ItemIndex := -1;   // RadioGroup: no radio button filled in
lstNames.ItemIndex  := -1;   // ListBox: nothing highlighted
Always check for -1 before reading a selection

If the user has not chosen anything, ItemIndex is -1. Reading cboMonth.Items[cboMonth.ItemIndex] while it is -1 causes a runtime error (list index out of bounds). Guard it first:

Delphi — safe reading
if cboMonth.ItemIndex = -1 then
  ShowMessage('Please select a month first.')
else
  sMonth := cboMonth.Text;

Naming Convention for Components

PrefixComponent
btnTButton
lblTLabel
edtTEdit
memTMemo
sedTSpinEdit
cboTComboBox
lstTListBox
rgpTRadioGroup
chkTCheckBox
pgcTPageControl
tmrTTimer
imgTImage
T3Term 3 · Timer & PageControl (PAT)

Timer Component

A TTimer fires its OnTimer event at regular intervals without user input.

PropertyMeaning
IntervalMilliseconds between triggers (1000 = 1 second)
EnabledTrue/False — starts or stops the timer
Delphi — countdown timer
var
  iSeconds: Integer;  // global variable

// OnTimer event (fires every 1000ms)
procedure TForm1.tmrCountTimer(Sender: TObject);
begin
  Dec(iSeconds);
  lblTime.Caption := IntToStr(iSeconds) + ' seconds left';
  if iSeconds <= 0 then
  begin
    tmrCount.Enabled := False;
    ShowMessage('Time is up!');
  end;
end;

PageControl (Tabbed Forms)

A TPageControl creates tabbed pages on a form. Each tab is a TTabSheet.

Creating tabs

  1. Add TPageControl to the form
  2. Right-click → New Page to add tabs
  3. Set each TTabSheet.Caption in the Object Inspector
  4. Drop other components onto each tab — they belong to that tab

Controlling tabs in code

Delphi
// Show a tab
TabSheet2.TabVisible := True;

// Hide a tab
TabSheet2.TabVisible := False;

// Jump to a specific tab
pgcMain.ActivePage := TabSheet3;
Grade 10 · Practical

Data Types & Variables Grade 10

Every value in Delphi has a data type. Variables are the containers that hold these values while your program runs. Constants hold values that never change.

T1Term 1 · Data Types, Variables & Constants

Data Types

Data TypeWhat it storesExamplesQuotes?
IntegerWhole numbers (positive & negative, no decimals)3, -15, 1250No
Int64Very large whole numbers (see below)3000000000No
RealNumbers with decimals (floating point)3.14, -13.24, 125.89No
StringOne or more characters — text'Banana', '23.45', '@!jkl'Single quotes '…'
CharA single character only'S', '!', 'a'Single quotes '…'
BooleanOnly True or FalseTrue, FalseNo
Integer and Real Values Mix — But Not Both Ways

Delphi lets you go one way but not the other: a whole-number result can be poured into a Real variable without any fuss, but a Real value can never be poured into an Integer variable — there is no automatic way to throw away a decimal part. Worth remembering too: the / operator always hands back a Real answer, even when both of the numbers you divide happen to be whole numbers.

Delphi
rTotalStock := iBoxesIn + iBoxesReturned;   // fine — a whole number fits happily into a Real
iBoxesIn    := rTotalStock * 2;             // rejected — a Real value won't fit into an Integer

When Integer Is Not Big Enough — Int64

An Integer can only hold whole numbers from about -2.1 billion to +2.1 billion (exactly -2 147 483 648 to 2 147 483 647). Go past that and the value overflows and gives a wrong answer, or crashes the program. For bigger whole numbers use Int64, which holds values up to about 9.2 × 1018.

A good example is money counted in cents: a municipal budget of R30 million is 3 000 000 000 cents, which is too big for an Integer. Another is a factorial: 13! is already 6 227 020 800, and Int64 can hold factorials up to 20!.

Delphi — Int64 for a big total
var
  iBudgetCents : Int64;     // Integer would overflow here
  iProjectCents : Integer;
begin
  iBudgetCents := 3000000000;
  iProjectCents := 950000000;
  iBudgetCents := iBudgetCents - iProjectCents;   // a smaller whole number fits into an Int64 happily
end;
Pick the smallest type that is safe

Use Integer for everyday counting (ages, marks, quantities). Reach for Int64 only when a total or a product could realistically pass 2 billion. Use Real instead when the value needs decimals — Int64 still holds whole numbers only.

Variables

A variable is a named storage location that holds a value during program execution. Think of it as a labelled cup — it holds one thing at a time, but you can empty it and refill it whenever you like.

Variables must be: Declared → Populated → Used.

ANALOGY — a variable is like a cup

A variable holds one value at a time, but the value can change. Your cup might hold coffee now, tea after break and hot chocolate tonight — same cup, different contents. In the same way iScore could be 5 now and 12 later.

The data type is the kind of container, and it decides what may go inside — just as a cup is made for liquids and a plate is made for food. Each type is its own kind of container:

  • Integer — holds whole numbers, e.g. 3, 15, −7
  • Real — holds numbers with decimals, e.g. 3.14
  • String — holds text, e.g. 'Banana'
  • Boolean — holds only True or False

And just as you would not serve soup on a plate, you cannot store the word 'Banana' in an Integer — the value has to match the type of container.

Rules for Variable Names

Delphi won't accept just any piece of text as a variable name — a handful of rules apply every time you choose one:

Multi-word Names

When a single word isn't descriptive enough, run several together and capitalise each new one instead of using spaces or an unbroken run of lowercase letters — sFirstName and rTotalCost read far more clearly than sfirstname or rtotalcost.

Naming Convention — Prefixes

PrefixData TypeExample
iIntegeriAge
rRealrPrice
sStringsName
cCharcGrade
bBooleanbFound

Declaring Variables

Declaring a variable means creating a named container that we can populate later, in the var section, using the format: variableName : DataType;

DECLARATION OF A VARIABLE Prefix to indicate datatype Semicolon to end statement s Name : string ; Variable name Colon instead of assignment sign (:=) Datatype of variable

Local Declaration (inside a procedure)

Delphi — Local
procedure TForm1.btnClickClick(Sender: TObject);
var
  sName:   string;
  iNumber: integer;
begin
  // code here
end;

Global Declaration (available to all procedures)

Delphi — Global
var
  Form1:   TForm1;
  sName:   string;   // declared here, below existing var block
  iNumber: integer;

Populating (Assigning) Variables

Use the assignment operator := to put a value into a variable that has already been declared.

POPULATING (ASSIGNING) A VARIABLE Variable being populated Semicolon to end statement sName := 'Jannie' ; Assignment operator — "becomes equal to" Value being stored — quotes mean it's a String
Delphi
sName   := 'Jannie';
sName   := edtName.Text;        // from a text box
iNumber := 15;
iNumber := sedNum.Value;         // from a spin edit
bFlag   := True;
ANALOGY — why we assign to the LEFT

The := operator always works right → left: it takes the value on the right and stores it in the variable on the left.

Think of pouring coffee. You put the coffee (the value) into the cup (the variable) — you would never put the cup into the coffee! So the container always goes on the left.

In sName := 'Jannie'; the coffee is 'Jannie' (on the right) and the cup is sName (on the left). Read it backwards: "take 'Jannie' and pour it into sName".

It works the same with a calculation: iTotal := iPrice * iQty; — work out the answer (the coffee) on the right first, then pour it into iTotal (the cup) on the left. This is also why 5 := iAge; is impossible — you cannot pour a variable into a plain number.

Initialising Variables

Always Initialise

Set a starting value before using a variable, especially counters and totals — otherwise Delphi may assign a random garbage value.

Delphi
i        := 0;
iTotal   := 0;
sReverse := '';
cLetter  := '';

Using Variables

Delphi
lblFullName.Caption := sName + ' ' + sSurname;
memOut.Lines.Add(sName + ' ' + sSurname);
iAnswer := iNum1 + iNum2;
memOut.Lines.Add(IntToStr(iNum1) + ' + ' + IntToStr(iNum2)
               + ' = ' + IntToStr(iAnswer));
Special Characters — New Lines and Tabs

Two ASCII character codes are handy for laying out text: #13 forces whatever follows onto a new line (it is the code for a carriage return), and #9 inserts a tab space. Join either one into a string with +, exactly like any other piece of text:

Delphi
lblResult.Caption := 'Test 1: 78%' + #13 + 'Test 2: 84%';
memOut.Lines.Add('Player' + #9 + 'Score');

Incrementing and Decrementing Variables

Instead of writing out a full assignment every time a counter needs to move up or down by one, Delphi gives you two ready-made procedures: Inc and Dec. Call one with just the variable name and it steps by one; give it a second number and it steps by that amount instead.

StatementEquivalent to
Inc(iVisitors);iVisitors := iVisitors + 1;
Inc(iVisitors, 5);iVisitors := iVisitors + 5;
Dec(iStock);iStock := iStock - 1;
Dec(iStock, 5);iStock := iStock - 5;
Handy for Counters

You'll reach for Inc most often inside a loop, nudging a counter forward one step per repetition — Inc(iCount); reads more naturally than repeating the full assignment statement every time.

Getting Input with InputBox

Not every value needs its own Edit box sitting on the form. The InputBox function opens a small dialog of its own, waits for the user to type something, and hands back whatever they entered — always packaged as a string, no matter what kind of data it looks like.

Delphi — InputBox(title, prompt, default)
sTeam := InputBox('House Team', 'Which house are you in?', '');

Since the result is always text, wrap it in a conversion function whenever you actually need a number or a single character:

Required typeExample
stringsTeam := InputBox('House Team', 'Which house are you in?', '');
integeriAge := StrToInt(InputBox('Age', 'How old are you?', ''));
realrHeight := StrToFloat(InputBox('Height', 'What is your height in metres?', ''));
charcGrade := InputBox('Grade', 'Enter your grade symbol:', '')[1]; — the [1] keeps only the first character typed

Constants

A constant holds a value that is known before the program runs and cannot change while it runs. Use const instead of var. No data type is needed, and use = not :=.

Delphi
const
  VAT       = 0.15;
  MAX_ITEMS = 100;

// Using a constant — exactly like a variable
rVatAmount := rCostPrice * VAT;
rTotal     := rCostPrice + rVatAmount;

Ordinal Types

An ordinal type is a type whose values can be listed in a fixed order, one after the other, so that every value has a definite next and previous value. Ordinal types are the only ones allowed for a for loop counter, for the selector of a case statement, and for Inc, Dec and Ord.

OrdinalNot ordinal
Integer (and Int64) — after 7 comes 8Real — there are endless values between 2.5 and 2.6, so no value has a "next" one
Char — after 'C' comes 'D'String — text of any length has no single position in a list
Boolean — False then True
Enumerated and subrange types (below)
Why it matters

This is why you can write for cLetter := 'A' to 'Z' do or Inc(iCount), but you cannot write for rValue := 1.0 to 2.0 do or use a string as the selector of a case statement.

Enumerated Types

An enumerated type is a type you define by listing every value it may have, in words. A variable of that type can hold only one of the listed names, which makes your code easier to read than using codes like 1, 2 and 3. The list goes in a type section, near the top of the unit above the form class; the variable is then declared as normal.

Delphi — an enumerated type for fee payments
type
  TPayStatus = (Unpaid, Deposit, PaidInFull);   // the only three values allowed

procedure TForm1.btnCheckClick(Sender: TObject);
var
  ePay : TPayStatus;
begin
  ePay := Deposit;
  case ePay of
    Unpaid     : lblNote.Caption := 'Please pay the fees';
    Deposit    : lblNote.Caption := 'Balance still outstanding';
    PaidInFull : lblNote.Caption := 'Thank you';
  end;
  memOut.Lines.Add(IntToStr(Ord(ePay)));         // shows 1, the position in the list
end;

The values are numbered from 0 in the order you list them (Unpaid = 0, Deposit = 1, PaidInFull = 2), and Ord gives you that number. You can compare them, too: ePay < PaidInFull is True for both Unpaid and Deposit.

Trap — enumerated values are not text

You cannot assign 'Deposit' (in quotes) to an enumerated variable, and you cannot pass one straight into ShowMessage or IntToStr. Use a case statement to turn each value into the text you want to display, or Ord to get its number.

Subrange Types

A subrange type restricts an ordinal type to a stretch of its values. Write the lowest and highest value with two dots between them. It documents what values are legal, and lets Delphi catch mistakes — for instance a constant outside the range is rejected when you compile.

Delphi — subrange types
type
  TMark   = 0..100;       // whole numbers 0 to 100 only
  TLetter = 'A'..'E';     // only the characters A to E

var
  iMark : TMark;
  cSymbol : TLetter;
begin
  iMark   := 76;       // fine
  cSymbol := 'C';      // fine
  iMark   := 120;      // rejected: 120 is outside 0..100
end;
Enumerated or subrange?

Use an enumerated type when you have a small set of named choices (payment status, ticket type). Use a subrange when the values are ordinary numbers or letters but only part of the range makes sense (a mark, a month number 1..12). Neither replaces input validation: a value typed by the user still needs checking before it is stored.

Type Conversion

Components like TEdit only hold strings. You must convert to the right type before using in calculations.

FunctionConvertsExample
StrToInt()String → IntegeriAge := StrToInt(edtAge.Text);
StrToFloat()String → RealrPrice := StrToFloat(edtPrice.Text);
IntToStr()Integer → StringlblOut.Caption := IntToStr(iTotal);
FloatToStr()Real → StringlblOut.Caption := FloatToStr(rAverage);
The Val procedure — converting safely

StrToInt crashes (runtime error) if the text isn't a valid number. The Val procedure converts a string to a number without crashing: it gives back the converted value AND an error code that tells you whether the conversion worked (0 = success, otherwise the position of the first bad character).

Delphi — Val(sourceString, numberResult, errorPosition)
var
  iValue, iCode : Integer;
begin
  Val(edtAge.Text, iValue, iCode);
  if iCode = 0 then
    ShowMessage('Valid number: ' + IntToStr(iValue))
  else
    ShowMessage('Not a valid number!');   // iCode = position of the bad character
end;

The Str Procedure — Number to String

IntToStr and FloatToStr are functions: they hand the text back to you. Str does the same job as a procedure: you give it a number and a string variable, and it places the text in that variable. It can also format the number in the same step by writing value:width:decimals.

Delphi — Str(number, stringVariable)
var
  sCount, sPrice : string;
  rPrice : real;
begin
  rPrice := 24.5;
  Str(42, sCount);                    // sCount = '42'
  Str(rPrice:0:2, sPrice);             // sPrice = '24.50'
  lblOut.Caption := 'Price: R' + sPrice;
end;
Always format a Real with Str

Write the real value as rPrice:0:2 — the 0 means "use as much space as needed" and the 2 is the number of decimal places. Without the formatting part, a Real comes out in long scientific notation that is no use on a form.

Formatting Real Numbers

Delphi
// FloatToStrF(value, format, totalDigits, decimals)
lblPrice.Caption := FloatToStrF(rPrice, ffCurrency, 4, 2);  // → R24.50
lblPrice.Caption := FloatToStrF(rPrice, ffFixed,    4, 2);  // → 24.50
FormatDescription
ffCurrencyAdds a currency symbol to the formatted value
ffExponentWrites the value out in scientific notation
ffFixedRounds the value to however many decimal places you ask for
ffGeneralPlain number formatting — decimals are shown only when the value actually has them
ffNumberWorks like ffFixed, but breaks large numbers up with thousands separators

Types of Errors

Error TypeWhen it occursExample
Syntax ErrorCode is typed incorrectly — won't compileMissing semicolon, missing end
Runtime ErrorCrashes while the program is runningDividing by zero
Logical ErrorRuns, but gives wrong answerCalculating average before total, infinite loop

Only a syntax error stops the program from compiling at all — Delphi catches it immediately. Runtime and logical errors both let the program compile and run, which makes them harder to catch: a runtime error only shows itself when the exact conditions that break it occur (e.g. the user finally types a letter instead of a number), and a logical error may never show itself at all — the program keeps running and simply produces the wrong answer.

Common causes of runtime errorsCommon causes of logical errors
Converting text that isn't a valid number (StrToInt/StrToFloat)Using the wrong variable in a calculation (e.g. a property was never transferred into it)
Dividing by zeroGetting the sequence of instructions wrong (e.g. calculating a total before all the values were added)
Calculating the square root of a negative numberUsing AND/OR/NOT incorrectly in a compound condition
A calculated answer too big for its variable type (overflow)Ignoring the order of precedence of operators
Accessing an array index that is out of rangeA mistake with the variable controlling a loop, causing it to run forever
GIGO — the root cause of many errors

Many runtime and logical errors trace back to invalid data: Garbage In, Garbage Out. A program is only as reliable as the checks it makes on the data it receives — see Input Validation on the Decision Making page.

Preventing and Handling Runtime Errors with Try..Except

A try..except block protects against any runtime error, not just a bad conversion. Code that might fail — a conversion, a calculation, anything risky — goes inside the try section. The moment something in there raises an error, Delphi abandons whatever was left in that section and jumps straight to except, running the recovery code written there instead of letting the program crash.

Syntax
try
  // risky code that might raise a runtime error
except
  // code that runs only if an error occurred above
end;
Delphi — protecting a StrToFloat conversion
var
  rAmount : real;
begin
  try
    rAmount := StrToFloat(edtAmount.Text);
  except
    ShowMessage('Invalid amount entered');
  end;
end;
Val vs try..except

The Val procedure above and a try..except block solve the same problem in different ways. Val checks a conversion specifically and gives you an error code to test. try..except is more general — it protects any block of code (a conversion, a calculation, a file operation) and reacts only if something actually goes wrong.

Finding Logical Errors — Debugging Tools

Logical errors are the hardest to find because the program runs without crashing. Besides tracing the code by hand with a paper-based trace table, Delphi's built-in debugger lets you watch a program execute one line at a time and see exactly what is happening inside it.

ToolWhat it does
BreakpointClick in the grey margin next to a line of code to mark where execution must pause. When the program reaches that line, Delphi stops and lets you take control instead of running straight through.
Step (F8)Executes only the highlighted line, then pauses again on the next one — lets you watch the program run one instruction at a time.
Watch List (Run → Add Watch)Displays the current value of one or more variables, updated live as each line executes — so you can see exactly where a variable gets the wrong value.
Stop guessing, start watching

It is tempting to change lines of code at random when the output looks wrong, hoping something sticks. That approach wastes time and can introduce new bugs on top of the original one. Watching the variables change value one line at a time pinpoints the exact instruction responsible, so the fix is targeted instead of accidental.

Grade 10 · Practical

Operators & Functions Grade 10

Operators perform calculations. Delphi also has a rich library of built-in functions for maths, string handling, and more.

T1Term 1 · Operators, Precedence & Functions

Arithmetic Operators

OperatorSymbolDescriptionExampleResult
Addition+Add values5 + 38
Subtraction-Subtract10 - 46
Multiplication*Multiply4 * 312
Division/Divide (returns Real)7 / 23.5
Integer DivisionDIVWhole part only (no remainder)7 DIV 23
ModulusMODRemainder only7 MOD 21

MOD and DIV Examples

CalculationWorkingMOD resultDIV result
5 MOD/DIV 25 ÷ 2 = 2 remainder 112
25 MOD/DIV 525 ÷ 5 = 5 remainder 005
17 MOD/DIV 317 ÷ 3 = 5 remainder 225
Common Uses of MOD

Even/Odd check: n MOD 2 = 0 → even
Factor check: b MOD a = 0 → a is a factor of b
Last digit: n MOD 10 → last digit of n

Worked Example — Isolating the Digits of a Number

A favourite exam task: pull a number apart digit by digit. The trick is the pair MOD 10 (gives the last digit) and DIV 10 (chops the last digit off). Repeat in a loop until nothing is left. Here we add up the digits, e.g. 1234 → 1+2+3+4 = 10.

Delphi — sum the digits
var
  iNum, iDigit, iSum : Integer;
begin
  iNum := StrToInt(edtNum.Text);   // e.g. 1234
  iSum := 0;
  while iNum > 0 do
  begin
    iDigit := iNum mod 10;   // MOD 10 grabs the LAST digit  (1234 -> 4)
    iSum   := iSum + iDigit;
    iNum   := iNum div 10;   // DIV 10 chops it off          (1234 -> 123)
  end;
  lblSum.Caption := 'Digit sum: ' + IntToStr(iSum);
end;
Same trick, many questions

The MOD 10 / DIV 10 loop is the key to counting digits, reversing a number, checking for a palindrome, or building the Luhn check digit of an ID. Swap what you do with iDigit and you have solved a whole family of questions.

Worked Example — Complete Groups and Leftovers

Whenever items must be packed into groups of a fixed size, DIV and MOD work as a pair. DIV counts how many complete groups you can fill; MOD tells you how many items are left over once those groups are full.

Imagine the tuck shop has baked 134 cupcakes for a fundraiser and each box holds 12.

QuestionCalculationAnswer
How many full boxes?134 DIV 1211 (11 × 12 = 132)
How many cupcakes are left over?134 MOD 122 (134 − 132)
Check11 * 12 + 2134 — we got every cupcake back
Delphi — boxes and leftovers
const
  BOX_SIZE = 12;
var
  iCakes, iFullBoxes, iLeftover : Integer;
begin
  iCakes     := StrToInt(edtCakes.Text);     // e.g. 134
  iFullBoxes := iCakes div BOX_SIZE;      // 11 complete boxes
  iLeftover  := iCakes mod BOX_SIZE;      // 2 cupcakes that do not fill a box
  memOut.Lines.Add('Full boxes: ' + IntToStr(iFullBoxes));
  memOut.Lines.Add('Left over:  ' + IntToStr(iLeftover));
end;

The same pair converts a total into bigger and smaller units. A movie marathon of 435 minutes is 435 DIV 60 = 7 hours and 435 MOD 60 = 15 minutes — 7 h 15 min.

What if the leftovers also need a box?

The 2 leftover cupcakes still need somewhere to go, so the shop needs 12 boxes in total, not 11. You can get this by adding one extra box whenever the leftover is more than zero, or by rounding a real division up with Ceil (see Real Division with Floor and Ceil further down). Decide first whether the question wants complete groups or all items packed.

Operator Precedence (Order of Operations)

PriorityOperators
1st (highest)Brackets ( )
2nd*   /   DIV   MOD (left to right)
3rd (lowest)+   - (left to right)
Example
result := 2 + 3 * 4;         // = 14  (3*4 first)
result := (2 + 3) * 4;       // = 20  (brackets first)
result := 10 DIV 2 + 3;      // = 8   (DIV first)

Percentages — Discounts and Percentage Change

Percentages are just divisions by 100, so they are easy to calculate once you know which value goes where. Always store the amounts in Real variables, because money and percentages seldom come out as whole numbers.

Working Out a Discount

A discount is worked out like VAT, except that you subtract it instead of adding it. A school jersey costs R450 and is on sale at 12% off:

Delphi — price after a discount
const
  DISCOUNT_RATE = 12;     // percent
var
  rPrice, rDiscount, rFinal : Real;
begin
  rPrice    := 450;
  rDiscount := rPrice * DISCOUNT_RATE / 100;   // 450 * 12 / 100 = 54
  rFinal    := rPrice - rDiscount;                // 450 - 54 = 396
  lblFinal.Caption := FloatToStrF(rFinal, ffCurrency, 8, 2);
end;

A shortcut that gives the same answer: the customer pays (100 - 12) percent of the price, so rFinal := rPrice * (100 - DISCOUNT_RATE) / 100;.

Percentage Change

How much did something go up or down, compared with where it started? Subtract the old value from the new value, divide by the old value, and multiply by 100:

percentage change = (new − old) ÷ old × 100

A positive answer means an increase; a negative answer means a decrease.

SituationOldNewWorkingChange
Taxi fare goes upR18R21(21 − 18) / 18 × 100+16.67% (increase)
Sports bag on saleR650R520(520 − 650) / 650 × 100-20% (decrease)
Delphi — percentage change
var
  rOld, rNew, rChange : Real;
begin
  rOld    := StrToFloat(edtOld.Text);       // e.g. 650
  rNew    := StrToFloat(edtNew.Text);       // e.g. 520
  rChange := (rNew - rOld) / rOld * 100;     // -20
  lblChange.Caption := FloatToStrF(rChange, ffFixed, 8, 1) + '%';
end;
Trap — divide by the OLD value

The comparison always starts from where you began, so the old value is the denominator. Dividing by the new value gives the wrong answer. Also remember the brackets around (rNew - rOld) — without them, precedence would divide first. And if the old value could be 0, check for that before dividing.

Mathematical Functions

Add Math to your uses section to access power, floor, ceil etc.

FunctionDescriptionExampleResult
sqr(x)x squared (x²)sqr(4)16
sqrt(x)Square rootsqrt(16)4.0
power(x,n)x to the power of npower(5,3)125
round(x)Round to nearest integer (an exact .5 goes to the even neighbour — see below)round(5.68)6
trunc(x)Remove decimal (truncate)trunc(5.68)5
floor(x)Round DOWNfloor(3.76)3
ceil(x)Round UPceil(3.76)4
abs(x)Absolute value (remove negative)abs(-12)12
frac(x)Fractional part onlyfrac(12.75)0.75
piValue of πpi3.14159…
random(n)Random number from 0 to n-1random(10)0–9
RoundTo(x,-n)Round to n decimal placesRoundTo(12.3456,-2)12.35

Round, Trunc, Floor and Ceil — Which One?

All four turn a real number into a whole number, but they do it differently. Floor and Ceil need the Math unit; Round and Trunc do not.

ValueRoundTruncFloorCeil
2.73223
2.52223
3.54334
-2.7-3-2-3-2
Trap — Round does not always round .5 up

The rounding you learnt in primary school (always round .5 up) is not what Round does. Delphi uses "ties go to the even number", so Round(4.5) is 4 and Round(5.5) is 6. If you need a particular direction, use Floor or Ceil instead of Round.

Real Division with Floor and Ceil — How Many Do You Need?

Many counting questions follow the same pattern: use / (real division, so the decimals are kept), then decide which way to round the answer.

Round with…Use when…Typical wording
FloorYou may not exceed a limit, so a partly affordable item does not count."How many can I afford / fit / buy?"
CeilYou must cover everything, even if the last container is only partly used."How many are needed / required?"
Delphi — Floor: how many pies can R500 buy?
var
  rBudget, rPieCost : Real;
  iPies : Integer;
begin
  rBudget  := 500;
  rPieCost := 18.50;
  iPies := Floor(rBudget / rPieCost);   // 500 / 18.50 = 27.027... -> 27
end;

27 pies cost R499.50, which fits. A 28th pie would push the total to R518, which is over budget — so the partly affordable pie is thrown away.

Delphi — Ceil: how many minibus taxis for a school trip?
var
  iLearners, iSeats, iTaxis : Integer;
begin
  iLearners := 62;
  iSeats    := 15;
  iTaxis := Ceil(iLearners / iSeats);   // 62 / 15 = 4.133... -> 5
end;

Four taxis carry only 60 learners, so a fifth is needed for the last two. Every learner must get a seat, so we round up.

Why not just use Round?

Rounding to the nearest whole number can go the wrong way: Round(4.133) is 4 taxis and two learners are left standing, and Round(27.6) would be 28 pies and an overspent budget. Pick Floor or Ceil based on the situation, not on how close the decimal is. For whole numbers that are not negative, a DIV b gives the same answer as Floor(a / b).

Inc and Dec

ProcedureEffectExampleResult
Inc(x)Increment by 1Inc(5)6
Inc(x, n)Increment by nInc(5, 3)8
Dec(x)Decrement by 1Dec(5)4
Dec(x, n)Decrement by nDec(6, 4)2

Upcase and Trim

FunctionDescriptionExampleResult
UpCase(c)Convert single char to uppercaseUpCase('a')'A'
Trim(s)Remove spaces from both endsTrim(' Hello ')'Hello'
TrimLeft(s)Remove leading spacesTrimLeft(' Hi')'Hi'
TrimRight(s)Remove trailing spacesTrimRight('Hi ')'Hi'
T3Term 3 · Ord & Chr Functions

Ord and Chr

Ord and Chr convert between characters and their ASCII numeric codes.

FunctionDescriptionExampleResult
Ord(c)Character → ASCII integerOrd('A')65
Chr(n)ASCII integer → CharacterChr(65)'A'

Caesar Cipher Example

Delphi — Shift characters by a number
var
  sInput, sOutput: string;
  i, iShift: Integer;
begin
  sInput := InputBox('Text', 'Enter text:', 'ABC');
  iShift := StrToInt(InputBox('Shift', 'Enter shift (1-25):', '3'));
  sOutput := '';
  for i := 1 to Length(sInput) do
    // wrap back to 'A' after 'Z' using MOD 26
    sOutput := sOutput + Chr(Ord('A') + (Ord(sInput[i]) - Ord('A') + iShift) mod 26);
  ShowMessage('Shifted: ' + sOutput);  // ABC → DEF, XYZ → ABC
end;
Why the MOD 26?

Without it, shifting a letter near the end of the alphabet (like 'X', 'Y' or 'Z') pushes past 'Z' into punctuation characters instead of wrapping back to 'A'. Subtracting Ord('A') first converts the letter to a 0–25 range, MOD 26 wraps it, and adding Ord('A') back converts it to a real letter again.

Grade 10 · Practical

Decision Making — IF & CASE Grade 10

Decision structures let your program choose different paths based on conditions. Delphi uses if…then…else and case for this.

What is Decision Making?

Decision-making (also called conditional logic) is when a program tests whether something is true or false and then chooses what to do next based on the answer. A condition is any question that can only be answered with true or false — for example, "is the age 18 or more?".

Everyday analogy: A robot (traffic light) at an intersection makes a decision for you. If the light is green you go; else you stop. Your program does the same thing — it looks at a condition and takes one path or another.

Why Do Programs Need to Make Decisions?

Without decisions, a program could only ever do the exact same thing every single time it runs. Decisions make a program react to its data and its user.

T1Term 1 · Basic IF & IF…ELSE

The IF Statement

The IF statement evaluates a condition that must resolve to True or False, and executes a statement only when that condition is True.

In plain words it says: "If this is true, then do that; otherwise (else) do something else." Everyday analogy: "If it is raining, take an umbrella, else wear a cap." The "if it is raining" part is the condition that is checked first.

THE IF STATEMENT Keyword — starts every decision Keyword — leads into the action if iAge >= 18 then Condition — must evaluate to True or False

IF … THEN (one-way)

Syntax
if condition then
  statement;

IF … THEN … ELSE (two-way)

No semicolon before ELSE

Never put a ; on the line before else — it ends the if statement too early.

Syntax
if condition then
  statement
else
  statement;

Multiple Statements — use BEGIN…END

Delphi
if iAge >= 18 then
begin
  lblResult.Caption := 'Adult';
  btnVote.Enabled   := True;
end
else
begin
  lblResult.Caption := 'Minor';
  btnVote.Enabled   := False;
end;

Examples

Delphi
if iNum1 > iNum2 then
  ShowMessage(IntToStr(iNum1) + ' is larger');

if iAge >= 18 then
  ShowMessage('Old enough to vote');

if sUsername <> 'admin' then
  ShowMessage('Access denied')
else
  ShowMessage('Welcome, administrator!');

Comparison Operators

OperatorMeaningExample
=Equal toiAge = 18
<>Not equal tosName <> 'Admin'
>Greater thaniScore > 50
<Less thaniAge < 18
>=Greater than or equal toiMark >= 30
<=Less than or equal torPrice <= 100.0
T2Term 2 · Full IF…ELSE, Nested IF, Boolean Operators & CASE

Nested IF

An IF inside another IF.

Delphi
if iAge >= 18 then
begin
  if bHasLicense = True then
    bDrive := True
  else
    bDrive := False;
end
else
  bDrive := False;

Boolean Operators

Combine multiple conditions in one statement.

Boolean operators let you ask more than one question at the same time. Everyday analogy: to get into a club you might need to be 18 AND have an ID — both must be true. To qualify for a discount you might need to be a student OR a pensioner — either one is enough. NOT simply flips an answer around, like saying "if it is not a holiday, school is open".

OperatorRuleExample
ANDBoth conditions must be true(iAge >= 18) AND (bHasID = True)
ORAt least one condition must be true(sGender = 'M') OR (sGender = 'F')
NOTInverts the conditionNOT (iScore > 50)
Delphi — AND and OR examples
if (iAge >= 18) AND (bHasLicense = True) then
  bCanDrive := True;

if (iScore >= 30) OR (bHasSymbol = True) then
  lblResult.Caption := 'Passed';
Watch the order AND and OR are applied

When a condition mixes AND and OR without brackets, Delphi does not test them strictly left-to-right — NOT is applied first, then AND, and only then OR. This is the same idea as multiplication happening before addition in a maths expression. Two learners could type the exact same words and end up with logically different conditions, so get into the habit of bracketing every individual condition — it removes any doubt about what is being tested against what.

Shortcut — Assigning a Boolean Directly

Sometimes an entire if…then…else exists purely to store True or False in a Boolean variable. In that case the condition already is the answer you want, so the if is not needed at all — the condition can be assigned straight to the variable.

Delphi — two ways to record whether a learner passed
// Longer version:
if iMark >= 50 then
  bPassed := True
else
  bPassed := False;

// Shorter, equivalent version:
bPassed := iMark >= 50;

Simplifying a Long Condition with 'Flags'

A single if line that strings together many ANDs and ORs across several variables becomes hard to read, and one misplaced bracket can break the whole thing. A tidier approach is to work out each separate rule on its own line first, storing every result in its own Boolean variable (often called a flag), and letting the final decision combine only the flags.

Consider selecting a learner for the school athletics team: they must have run the trial faster than the qualifying time, attended at least 80% of the practice sessions, and not currently be under a sports suspension.

Delphi — team selection built from three flags
var
  bFastEnough, bAttendedEnough, bMaySelect : boolean;
  rTrialTime, rQualifyTime, rAttendancePercent : real;
  bSuspended : boolean;
begin
  bFastEnough     := rTrialTime <= rQualifyTime;
  bAttendedEnough := rAttendancePercent >= 80;
  bMaySelect      := NOT bSuspended;

  if bFastEnough AND bAttendedEnough AND bMaySelect then
    lblResult.Caption := 'Selected for the team'
  else
    lblResult.Caption := 'Not selected';
end;
Why this is worth doing

Each flag can be checked on its own, which makes it much easier to spot a mistake in one rule without untangling a single sprawling condition. The final decision then reads almost like plain English.

The IN Operator

Tests if a value is in a set. Cleaner than multiple OR conditions.

Delphi
// Check for specific values
if iNumber IN [1, 3, 5, 7] then
  ShowMessage('Odd single digit found');

// Range using ..
if iMark IN [0..49] then
  lblSymbol.Caption := 'F';

// Works with Char too
if cLetter IN ['A', 'E', 'I', 'O', 'U'] then
  ShowMessage('Vowel');

Sets, Ordinal Types & Sub-Ranges

Everything written inside those square brackets is called a set. Sets only work with ordinal data types — types where every value has one clear predecessor and one clear successor, so the values can be counted off in order. Integer, Char and Boolean all qualify. Real and String do not: between any two real numbers there are infinitely many more real numbers, so there is no single "next" one, which rules them out of a set.

Instead of listing every value separately, a sub-range lets you give just the two endpoints as <lowest> .. <highest>. A single set is allowed to mix plain values and sub-ranges together, separated by commas:

Delphi — a grade band and a seating rule built from sub-ranges
if cGrade IN ['A'..'C'] then
  ShowMessage('Well done — top achiever!');

if NOT (iSeat IN [1..15, 40..55]) then
  ShowMessage('Seat number must be 1-15 or 40-55');
Set limits

A sub-range built from Integers can only test values between 0 and 255 — anything outside that band raises an error. A set is also capped at a maximum of 265 values in total.

Decision Components

RadioGroup

Uses an ItemIndex property — first item is index 0.

Delphi
if rgpGender.ItemIndex = 0 then
  sGender := 'Male'
else
  sGender := 'Female';

CheckBox

Uses the Checked property — True or False.

Delphi
if chkInsurance.Checked = True then
  rCost := rCost + rInsuranceAmount;

The CASE Statement

Cleaner alternative to multiple IF…ELSE when testing one variable against many values. Works with Integer and Char only.

Use CASE when one variable could take many possible values and each value leads to a different outcome — like turning a mark into a grade symbol. Everyday analogy: a vending machine. You press one button (the value), and depending on which button it was, a different snack drops out. Writing that as a long chain of IF…ELSE statements works, but CASE lays it out neatly so it is much easier to read.

Syntax
case expression of
  value1: statement1;
  value2: statement2;
  value3: statement3;
else
  statementDefault;
end;
Remember

CASE has no begin, but always has end. You can use ranges with ..

Delphi — Grade symbol example
case iMark of
  80..100: lblSymbol.Caption := '7 — Outstanding';
  70..79:  lblSymbol.Caption := '6 — Meritorious';
  60..69:  lblSymbol.Caption := '5 — Substantial';
  50..59:  lblSymbol.Caption := '4 — Adequate';
  40..49:  lblSymbol.Caption := '3 — Moderate';
  30..39:  lblSymbol.Caption := '2 — Elementary';
else
  lblSymbol.Caption := '1 — Not Achieved';
end;

What Can Go in a CaseList

The value being tested (the Selector Expression, straight after the word case) must be ordinal. Each individual caseList is flexible about how it lists the values it matches — it can be one constant on its own, several constants separated by commas, a sub-range, or any mixture of these on the same line. The only rule is that a value may not show up in two different caseLists.

Delphi — bus fare worked out from the zone number
case iZone of
  1             : rFare := 12;
  2, 3          : rFare := 18;
  4..6          : rFare := 25;
  7, 8, 10..12 : rFare := 35;
end;

A caseList is not restricted to a single statement either — wrap several statements in begin…end exactly as you would for a multi-statement IF:

Delphi — tallying a register by arrival time
case iArrivalMinutes of
  0..5    : Inc(iOnTime);
  6..15   : Inc(iLate);
  16..60  : begin
                Inc(iLate);
                Inc(iVeryLate);
              end
else
  ShowMessage('Please check the time entered');
end; // end of case
Two easy mistakes to avoid

Only one caseList can fire per run of the statement, so double-check that your ranges don't overlap. And remember there is never a semicolon directly before the else part — the same rule as an IF statement. If a CASE branch needs to abandon the rest of the procedure entirely (say, after finding invalid data), call Exit — it stops any further processing in that procedure or function, and works anywhere in one, not only inside a CASE. (How Exit differs from Break is explained on the Loops page.)

MessageDlg

A pop-up dialog that asks the user a yes/no question and returns a result.

Delphi
if MessageDlg('Are you sure?', mtConfirmation, mbYesNo, 0) = mrYes then
  // execute if user clicked Yes
  ShowMessage('Confirmed!');
ParameterOptions
Message typemtConfirmation, mtInformation, mtWarning, mtError
ButtonsmbYesNo, mbOKCancel, mbYesNoCancel
ResultmrYes, mrNo, mrOK, mrCancel

Input Validation

No amount of clever code can rescue a program that starts with bad data — this is often summed up as GIGO: Garbage In, Garbage Out. Before a program uses a value in a calculation or a decision, it should first check that the value is reasonable. Checking a value before it gets used is called input validation, and the IF statement is the tool most often used to do it.

It helps to separate two ideas that are easy to confuse:

A validation rule spells out exactly what "valid" means for a piece of data, for example: "the number of matric dance tickets ordered must be a whole number from 1 to 6." Once the rule is written down, an IF statement can enforce it:

Delphi — range check
if (iTickets < 1) or (iTickets > 6) then
  ShowMessage('You may order between 1 and 6 tickets.');

Validation matters most when an invalid value would otherwise crash the program during a calculation. Delphi's Sqrt function, for instance, cannot handle a negative number, so the sign has to be checked first:

Delphi — check before Sqrt
if rNumber < 0 then
  ShowMessage('Cannot calculate the square root of a negative number')
else
  rAnswer := Sqrt(rNumber);
Keep asking until the answer is valid

A single warning message still leaves the program with no usable value to work with. Wrapping the input and the check in a REPEAT..UNTIL loop forces the user to keep trying until they enter something acceptable:

Delphi — repeat until valid
repeat
  iTickets := StrToInt(edtTickets.Text);
  if not (iTickets in [1..6]) then
    ShowMessage('You may order between 1 and 6 tickets.');
until iTickets in [1..6];

A range is only one kind of validation rule. Depending on the field, a program might instead need to check:

Worked Example — Validate, Grade & Decide

A typical question chains several decisions together: first validate the input with an if, then use a case to map the mark to a symbol, then a final if to decide pass/fail. This shows exactly when to reach for if and when for case.

Delphi — mark → symbol → result
procedure TForm1.btnGradeClick(Sender: TObject);
var
  iMark   : Integer;
  sSymbol : string;
begin
  iMark := StrToInt(edtMark.Text);

  // 1. Validate first — reject impossible marks (IF with OR)
  if (iMark < 0) or (iMark > 100) then
  begin
    ShowMessage('A mark must be between 0 and 100.');
    Exit;                       // stop here — don't grade an invalid mark
  end;

  // 2. Map the mark to a symbol — CASE handles the many bands neatly
  case iMark of
    80..100: sSymbol := '7';
    70..79:  sSymbol := '6';
    60..69:  sSymbol := '5';
    50..59:  sSymbol := '4';
    40..49:  sSymbol := '3';
    30..39:  sSymbol := '2';
  else
    sSymbol := '1';
  end;

  // 3. A final pass/fail decision (IF)
  if iMark >= 50 then
    lblResult.Caption := 'Symbol ' + sSymbol + ' - PASS'
  else
    lblResult.Caption := 'Symbol ' + sSymbol + ' - needs improvement';
end;
IF or CASE — how to choose

Use CASE when one variable maps to many ranges or values (the mark → symbol step). Use IF for a true/false test or when conditions combine different variables (the validation and the pass/fail steps). The pattern validate → work out → decide appears in almost every practical question.

Grade 10 · Practical

Loops Grade 10

Loops repeat a block of code multiple times. Delphi has three loop types — choose based on whether you know how many times to repeat.

T3Term 3 · Loops & Repetition Structures

What is a Loop?

A loop is a programming structure that repeats a block of code over and over until a certain point is reached. Instead of writing the same instruction many times, you write it once and tell the computer how often, or until when, to repeat it.

Everyday analogy: Think of doing push-ups. The coach does not shout "do a push-up" fifty separate times. He says "do fifty push-ups." That single instruction, repeated until you reach fifty, is a loop. The action (one push-up) is the loop body, and "fifty" is the condition that tells you when to stop.

Why Do We Use Loops?

Loops save us from repeating ourselves and let programs handle any amount of work with the same short piece of code.

The Three Loop Types in Plain Words

Choosing the right loop comes down to one question: do you know in advance how many times to repeat?

Types of Loops

LoopTypeUse when…
for … doUnconditional (fixed)You know exactly how many times
while … doConditional (pre-test)Repeat WHILE a condition is true — check first
repeat … untilConditional (post-test)Repeat UNTIL a condition is true — always runs at least once

FOR Loop (Fixed / Unconditional)

Runs a set number of times. The counter increments or decrements automatically.

We call it fixed or unconditional because the number of repeats is decided before the loop even starts and cannot change while it runs. You give it a start value and an end value, and Delphi handles the counting for you — you never have to add 1 to the counter yourself.

WHEN TO USE

Reach for a FOR loop whenever you can finish the sentence "do this exactly ___ times" with a number — printing 1 to 10, working through all 30 learners in a class, or drawing 12 rows of a table.

THE FOR LOOP Keyword — starts the loop Keyword — leads into the repeated code for i := 1 to 5 do Counter — created and incremented automatically Start value End value — loop stops once this is reached
Syntax — counting UP
for counter := lowest to highest do
begin
  // code repeated each iteration
end;
Delphi — print 1 to 5
for i := 1 to 5 do
begin
  memOut.Lines.Add(IntToStr(i));
end;

FOR … DOWNTO (counting down)

Delphi — countdown 5 to 1
for i := 5 downto 1 do
begin
  memOut.Lines.Add(IntToStr(i));
end;

FOR Loop — Running Total

Delphi — sum 1 to 10
var
  i, iTotal: Integer;
begin
  iTotal := 0;  // initialise!
  for i := 1 to 10 do
    iTotal := iTotal + i;
  lblTotal.Caption := 'Sum = ' + IntToStr(iTotal);
end;

FOR Loop — the Counter Can Be Any Ordinal Type

A FOR loop's counter does not have to be an Integer — it can be declared as any ordinal type, provided the start value, end value and the counter variable itself all agree on that type. A Char counter, for instance, steps through the alphabet one letter at a time instead of counting through numbers.

Delphi — listing the letters 'B' to 'F'
var
  cLetter: char;
begin
  for cLetter := 'B' to 'F' do
    memOut.Lines.Add(cLetter);
end;
Keep the case consistent

A start value in uppercase paired with an end value in lowercase (or the reverse) will not behave the way you expect — uppercase and lowercase letters occupy separate blocks in the ASCII table, so mixing them changes how far apart the two values actually are, and therefore how many times the loop runs. Pick one case and stick to it for both bounds.

WHILE … DO Loop (Pre-Conditional)

Checks the condition before each iteration. If the condition is false from the start, the loop body never runs.

We call it pre-conditional ("pre" = before) because it tests the condition first, and only then decides whether to run the body. This makes it the safe choice when there is a chance the loop should not run at all.

WHEN TO USE

Use WHILE when you do not know how many repeats you need and it might be zero — for example, "keep reading numbers while the user hasn't typed 0". If they type 0 immediately, you correctly do nothing.

Syntax
while condition do
begin
  // code
end;

The ITC-Principle

A handy checklist for building a correct WHILE loop is the ITC-principle — three things that must all be true of your code, in this order:

StepWhat to check
InitialiseHas every variable used in the WHILE condition already been given a starting value before the loop is reached?
TestIs that condition re-checked at the top of every pass, deciding whether the body runs again?
ChangeDoes something inside the body actually update the variable(s) being tested? Without this step the condition can never turn False.
Avoid Infinite Loops

The counter must be initialised before the loop and incremented inside the loop — otherwise it runs forever and crashes your program. Also never put a ; straight after the do keyword — while condition do; creates an empty loop body, so the statement that was meant to change the condition is skipped, and the loop runs forever.

Delphi — while counter ≤ 5
var
  Counter: Integer;
begin
  Counter := 1;           // initialise BEFORE loop
  while Counter <= 5 do
  begin
    memOut.Lines.Add('Counter: ' + IntToStr(Counter));
    Inc(Counter);          // increment INSIDE loop
  end;
end;

WHILE — Reading user input until sentinel

Delphi — keep adding until user enters 0
var
  iNum, iTotal: Integer;
begin
  iTotal := 0;
  iNum   := StrToInt(InputBox('Input', 'Enter number (0 to stop):', ''));
  while iNum <> 0 do
  begin
    iTotal := iTotal + iNum;
    iNum   := StrToInt(InputBox('Input', 'Enter number (0 to stop):', ''));
  end;
  lblTotal.Caption := 'Total: ' + IntToStr(iTotal);
end;

Letting the User Interrupt a Loop While It Runs

A different situation arises when nobody knows how many times a loop should run until the user physically clicks a [Stop] Button partway through — a reaction game or a live counter are typical examples. This needs a Boolean variable that both the button that starts the loop and the button that stops it can share, so it must be declared in the private section of the form (giving it class scope) rather than inside a single procedure.

Delphi — a running counter the user can interrupt
private
  bRunning : boolean;   // shared by both button handlers below

procedure TForm1.btnGoClick(Sender: TObject);
var
  iTick : byte;
begin
  bRunning := True;
  iTick    := 0;
  while bRunning do
  begin
    Inc(iTick);
    memLog.Lines.Add(IntToStr(iTick));
    Sleep(300);                    // short pause so the numbers are readable
    Application.ProcessMessages;   // give the form a chance to react to the click
  end;
end;

procedure TForm1.btnHaltClick(Sender: TObject);
begin
  bRunning := False;
end;
Why Application.ProcessMessages matters here

A Delphi form normally deals with one event at a time, finishing the current event handler completely before looking at the next. While btnGoClick is stuck inside its loop, a click on [Halt] just waits in a queue rather than running immediately. Application.ProcessMessages is a command that tells the program to pause for a moment and clear that queue — handling any waiting clicks — before the loop carries on. Leave it out, and the [Halt] click is never processed until the loop finishes on its own, which defeats the purpose of having a stop button at all.

REPEAT … UNTIL Loop (Post-Conditional)

Runs the body first, then checks the condition. Guaranteed to run at least once. Loop continues while condition is false; stops when it becomes true.

We call it post-conditional ("post" = after) because it does the work first and asks the question afterwards. That is the opposite of the WHILE loop, and it is exactly what you want when the action must happen at least one time no matter what.

WHEN TO USE

Use REPEAT…UNTIL when the body must run at least once — like showing a menu and asking the user to choose, or asking for a valid mark and re-asking until they get it right. You always ask once, then keep asking until the answer is acceptable.

Syntax
repeat
  // code
until condition;

REPEAT follows the same three checks as the WHILE loop's ITC-principle, only in a swapped order — Initialise, Change, then Test — since the body always fires once before the condition is ever looked at. Lining the two loops up side by side shows how they really are opposites of each other:

While loopRepeat loop
Suited to situations where it is fine for the loop to run zero times.Suited to situations where the body must run at least once.
Keeps looping while the condition stays True.Keeps looping until the condition finally becomes True.
Order of checks: ITC — Initialise, Test, Change.Order of checks: ICT — Initialise, Change, Test.
Prefer >= over = in a termination test

Testing for an exact match can trap you in an infinite loop if the value ever skips straight past the target — for example a running score that jumps from 46 to 52 will never satisfy until iScore = 50. Writing until iScore >= 50 instead guarantees the loop will stop even if the value overshoots.

Delphi — repeat until i = 10
var
  i: Integer;
begin
  i := 1;
  repeat
    memOut.Lines.Add(IntToStr(i));
    i := i + 1;
  until i > 10;
end;

REPEAT — Validate input

Delphi — keep asking until valid mark
var
  iMark: Integer;
begin
  repeat
    iMark := StrToInt(InputBox('Mark', 'Enter mark (0-100):', ''));
    if (iMark < 0) OR (iMark > 100) then
      ShowMessage('Invalid! Enter 0-100');
  until (iMark >= 0) AND (iMark <= 100);
end;

Worked Example — Count, Average & Highest

One loop can gather several answers at once. Here we read marks until the user enters -1, and while looping we keep a counter, a running total and the highest so far — then work out the average at the end.

Delphi — statistics from a loop
var
  iMark, iCount, iTotal, iHighest : Integer;
  rAverage : Real;
begin
  iCount   := 0;      // initialise all three trackers before the loop
  iTotal   := 0;
  iHighest := 0;

  iMark := StrToInt(InputBox('Marks', 'Enter a mark (-1 to stop):', ''));
  while iMark <> -1 do
  begin
    Inc(iCount);                 // how many so far
    iTotal := iTotal + iMark;    // running total
    if iMark > iHighest then    // track the maximum
      iHighest := iMark;
    iMark := StrToInt(InputBox('Marks', 'Enter a mark (-1 to stop):', ''));
  end;

  if iCount > 0 then            // guard against dividing by zero
  begin
    rAverage := iTotal / iCount;
    memOut.Lines.Add('Count:   ' + IntToStr(iCount));
    memOut.Lines.Add('Average: ' + FloatToStrF(rAverage, ffFixed, 4, 1));
    memOut.Lines.Add('Highest: ' + IntToStr(iHighest));
  end
  else
    ShowMessage('No marks were entered.');
end;
The pattern

Initialise your trackers before the loop, update them inside it (add to the total, compare for the highest), and report after it. Always check iCount > 0 before dividing, or an empty run will crash with a divide-by-zero.

Comparison: Which Loop to Use?

SituationBest Loop
Print numbers 1 to 100for
Read until user types "stop"while or repeat
Must run at least once (e.g. menu)repeat
Unknown number of iterationswhile or repeat
Process each element in an arrayfor

Loop Control — How a Loop Is Controlled

Beyond picking FOR, WHILE or REPEAT, it is useful to describe what decides when a loop stops. This splits loops into two broad groups: definite repetition, where the number of passes can be worked out ahead of time, and indefinite repetition, where it cannot.

Counter Controlled Loops (Definite Repetition)

A counter controlled loop relies on a variable that starts at a known value, changes by a predictable amount on every pass, and is compared to a fixed target to decide whether to continue.

Because that change is predictable, you can always calculate in advance exactly how many times a counter controlled loop will run — a FOR loop is the most obvious example, but a WHILE or REPEAT loop built around a simple counter is counter controlled too.

Delphi — counter controlled WHILE loop: 8 times table
iRow := 1;
while iRow <= 10 do
begin
  iResult := iRow * 8;
  memOut.Lines.Add(IntToStr(iRow) + ' x 8 = ' + IntToStr(iResult));
  iRow := iRow + 1;
end; {while}

Sentinel Controlled Loops (Indefinite Repetition)

A sentinel controlled loop watches for a special "stop" value — a sentinel — typed in by the user. That value is only ever compared, never used in a calculation, since its whole job is to signal "no more data."

The "WHILE — Reading user input until sentinel" example further up this page is a sentinel controlled loop: 0 is the signal that tells it to stop. Since nobody can predict how many real numbers the user will enter before typing that sentinel, the number of passes is unknown in advance — which is why sentinel controlled loops fall under indefinite repetition.

Result Controlled Loops (Indefinite Repetition)

A result controlled loop keeps going until a particular outcome has actually happened — it is not driven by a counter reaching a target or a user typing a sentinel, but by whatever condition the program is watching for finally becoming true.

Delphi — spin a wheel of 8 prizes until the jackpot slot comes up
iSpins := 0;
repeat
  iSlot := Random(8) + 1;
  Inc(iSpins);
until iSlot = 8;
ShowMessage('Jackpot landed after ' + IntToStr(iSpins) + ' spins');

Nothing here counts down towards a known number of repeats, and there is no value the user types to signal "stop" — the loop simply keeps spinning until the result it is watching for (slot 8) actually comes up.

Nested Loops

A nested loop is simply a loop placed inside the body of another loop. Each time the outer loop takes one step, the inner loop runs through its entire range from start to finish before the outer loop is allowed to take its next step. The inner and outer loops don't have to be the same kind — a FOR loop can quite happily sit inside a WHILE loop, or inside another FOR loop.

Suppose an exam venue needs a code for every seat: a block letter ('A' to 'C'), a row number (1 to 3) and a seat letter within the row ('a' to 'c'). Three nested FOR loops can generate the complete list in one go.

Delphi — three nested FOR loops listing every seat code
procedure TfrmVenue.btnListSeatsClick(Sender: TObject);
var
  iRow : integer;
  cBlock, cSeat : char;
  iSeatCount : integer;
  sSeatCode : string;
begin
  iSeatCount := 0;
  for cBlock := 'A' to 'C' do       // outer loop
  begin
    for iRow := 1 to 3 do          // middle loop
    begin
      for cSeat := 'a' to 'c' do       // inner loop
      begin
        sSeatCode := cBlock + IntToStr(iRow) + cSeat;
        Inc(iSeatCount);
        memSeats.Lines.Add(sSeatCode);
      end; // for cSeat
    end; // for iRow
  end; // for cBlock
  memSeats.Lines.Add('Total seats = ' + IntToStr(iSeatCount));
end;
Tracing the order the loops fire

Follow the innermost loop first: cSeat runs all the way through 'a', 'b', 'c' before iRow is even allowed to move on to its next value. Only once iRow has itself been through 1, 2 and 3 — meaning the middle loop has fully finished for the current block — does cBlock step forward to its next letter. The resulting list reads A1a, A1b, A1c, A2a, A2b, A2c, A3a, A3b, A3c, B1a, … and finishes at Total seats = 27, since 3 blocks × 3 rows × 3 seats gives 27 combinations in total.

Stopping Early — Break and Exit

Sometimes you need to stop part-way through, without waiting for a loop to finish naturally or a procedure to reach its last line. Delphi has two commands for this. They look similar, but they stop different amounts of the code, so learners often mix them up.

BreakExit
What it stopsStops the rest of the loop from processingStops any further processing in that procedure or function
Where the program carries onWith the first line after the loop — the rest of the procedure still runsIt doesn't — control goes straight back to whoever called the procedure
Where it can be usedOnly inside a loop (FOR, WHILE or REPEAT)Anywhere in a procedure or function, inside a loop or not

Break — leave the loop, keep going with the procedure

In this example the user enters up to five marks, but typing a negative number means "I'm done". Break ends the loop at that point, and the line that displays the total still runs because it comes after the loop.

Delphi — Break stops the loop only
procedure TForm1.btnTotalClick(Sender: TObject);
var
  i, iMark, iTotal : integer;
begin
  iTotal := 0;
  for i := 1 to 5 do
  begin
    iMark := StrToInt(InputBox('Input', 'Mark (negative to stop):', ''));
    if iMark < 0 then
      Break;                 // rest of the loop is skipped...
    iTotal := iTotal + iMark;
  end;
  lblTotal.Caption := 'Total: ' + IntToStr(iTotal);   // ...but this line still runs
end;

Exit — leave the whole procedure

Here a negative mark is treated as an error instead. Exit abandons the procedure on the spot, so the total is never displayed.

Delphi — Exit stops the whole procedure
procedure TForm1.btnTotalClick(Sender: TObject);
var
  i, iMark, iTotal : integer;
begin
  iTotal := 0;
  for i := 1 to 5 do
  begin
    iMark := StrToInt(InputBox('Input', 'Mark:', ''));
    if iMark < 0 then
    begin
      ShowMessage('Marks cannot be negative');
      Exit;                  // nothing else in this procedure runs
    end;
    iTotal := iTotal + iMark;
  end;
  lblTotal.Caption := 'Total: ' + IntToStr(iTotal);   // never reached after Exit
end;
Trap — Break vs Exit

Ask yourself: "Should the code after the loop still run?" If yes, use Break. If no — the whole procedure should stop — use Exit. Also remember that Break in a nested loop only stops the loop it is written in; the outer loop carries on.

Number Algorithms with Loops

Loops really show their strength when you combine them with MOD and DIV to investigate numbers. The algorithms below are the standard ones: each is written first as plain steps, then as Delphi code, then checked with a small trace. Use uses Math for Power in the later examples.

The idea behind most of them

a MOD b = 0 means b divides exactly into a, so b is a factor of a. Test every possible divisor with a loop and you can answer almost any question about factors.

Listing All the Factors of a Number

  1. Start with an empty text variable for the answers.
  2. For every divisor from 1 up to the number itself:
  3. If the number MOD the divisor is 0, add the divisor to the text.
Delphi — all factors of a number
var
  iNumber, iDivisor : Integer;
  sFactors : string;
begin
  iNumber  := StrToInt(edtNumber.Text);      // e.g. 36
  sFactors := '';
  for iDivisor := 1 to iNumber do
    if iNumber mod iDivisor = 0 then
      sFactors := sFactors + IntToStr(iDivisor) + ' ';
  lblOut.Caption := sFactors;                // 1 2 3 4 6 9 12 18 36
end;
iDivisor36 MOD iDivisorFactor?
10Yes — added
20Yes — added
30Yes — added
40Yes — added
51No
60Yes — added
71No
84No
90Yes — added

The table stops at 9 to save space, but the loop carries on all the way to 36. Notice that both 1 and the number itself are always factors.

Prime and Composite Numbers

A prime number is greater than 1 and has exactly two factors: 1 and itself. A composite number is greater than 1 and has more than two factors. The number 1 is neither, because it has only one factor.

So the algorithm is to count the factors with the same loop as above, then judge the count.

  1. Set the factor count to 0.
  2. For every divisor from 1 up to the number: if the number MOD the divisor is 0, add 1 to the count.
  3. If the number is greater than 1 and the count is exactly 2, it is prime.
  4. If the number is greater than 1 and the count is more than 2, it is composite.
Delphi — prime, composite or neither
var
  iNumber, iDivisor, iCount : Integer;
  bPrime, bComposite : Boolean;
begin
  iNumber := StrToInt(edtNumber.Text);       // e.g. 31
  iCount  := 0;                             // initialise BEFORE the loop
  for iDivisor := 1 to iNumber do
    if iNumber mod iDivisor = 0 then
      Inc(iCount);

  bPrime     := (iNumber > 1) and (iCount = 2);
  bComposite := (iNumber > 1) and (iCount > 2);

  if bPrime then
    lblOut.Caption := 'Prime'
  else if bComposite then
    lblOut.Caption := 'Composite'
  else
    lblOut.Caption := 'Neither prime nor composite';
end;
NumberFactors foundiCountResult
311, 312Prime
211, 3, 7, 214Composite
111Neither
Trap — the number 1

Do not shortcut the composite test to bComposite := NOT bPrime. That would call 1 (and 0) composite, when they are neither. Keep the iNumber > 1 check in both tests so the rules match the definitions exactly, and keep the brackets around each comparison.

Stopping early

Once the count reaches 3 the number can no longer be prime, so you could leave the loop with Break (see Stopping Early above) instead of testing every remaining divisor. The simple full loop is still the one to learn first.

Perfect Squares

A perfect square is a whole number multiplied by itself, such as 49 (7 × 7) or 81 (9 × 9). No loop is needed: take the square root, chop off the decimals with Trunc, square the result, and see whether you get the original number back. If the square root had decimals, the square of the chopped value cannot match. (Use a non-negative number, because Sqrt of a negative value is a runtime error.)

Delphi — perfect square check
var
  iNumber, iRoot : Integer;
  bSquare : Boolean;
begin
  iNumber := StrToInt(edtNumber.Text);       // e.g. 81
  iRoot   := Trunc(Sqrt(iNumber));           // Sqrt(81) = 9.0  -> 9
  bSquare := (iRoot * iRoot) = iNumber;      // 9 * 9 = 81 -> True
end;

With 50: Sqrt(50) is 7.07…, Trunc gives 7, and 7 × 7 = 49, which is not 50, so 50 is not a perfect square.

Perfect Numbers

A perfect number equals the sum of its proper factors — all its factors except the number itself. For 28 the proper factors are 1, 2, 4, 7 and 14, and 1 + 2 + 4 + 7 + 14 = 28, so 28 is perfect. For 12 they add up to 1 + 2 + 3 + 4 + 6 = 16, so it is not.

No proper factor can be bigger than half the number, so the loop only needs to run from 1 to iNumber DIV 2. That also keeps the number itself out of the sum.

Delphi — perfect number check
var
  iNumber, iDivisor, iSum : Integer;
  bPerfect : Boolean;
begin
  iNumber := StrToInt(edtNumber.Text);       // e.g. 28
  iSum    := 0;
  for iDivisor := 1 to iNumber div 2 do   // 1 to 14
    if iNumber mod iDivisor = 0 then
      iSum := iSum + iDivisor;
  bPerfect := iSum = iNumber;
end;
Trap — do not add the number itself

If the loop ran up to iNumber, the number would be added as its own factor and every number would fail the test (the sum would always be too big). Stopping at iNumber DIV 2 avoids that.

Factorial

The factorial of n, written n!, is every whole number from 1 up to n multiplied together. So 7! = 1 × 2 × 3 × 4 × 5 × 6 × 7 = 5 040. By definition 0! = 1.

  1. Set a running product to 1.
  2. For every counter value from 1 up to n, multiply the product by the counter.
Delphi — factorial with a FOR loop
var
  i, iNumber : Integer;
  iFactorial : Int64;
begin
  iNumber    := StrToInt(edtNumber.Text);    // e.g. 7
  iFactorial := 1;                          // start at 1, NOT 0
  for i := 1 to iNumber do
    iFactorial := iFactorial * i;
  lblOut.Caption := IntToStr(iFactorial);    // 5040
end;
iiFactorial after the pass
(before loop)1
11
22
36
424
5120
6720
75040
Why Int64?

Factorials grow very quickly: 13! is already 6 227 020 800, which is too big for an Integer. An Int64 variable can hold factorials up to 20!. If iNumber is 0 the loop does not run at all, so the answer stays at 1 — exactly right for 0!. The same calculation can also be written with recursion; see the Grade 12 Recursion page.

The Fibonacci Sequence

In the Fibonacci sequence each term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …. A loop keeps track of the previous and current terms, builds the next one, and then slides both along.

  1. Set previous to 0 and current to 1, and start with an empty text variable.
  2. Repeat for the number of terms wanted:
  3. Add the previous term to the text; then next := previous + current; previous := current; current := next.
Delphi — the first ten Fibonacci terms
var
  i, iTerms, iPrev, iCurr, iNext : Integer;
  sSeries : string;
begin
  iTerms  := 10;
  iPrev   := 0;
  iCurr   := 1;
  sSeries := '';
  for i := 1 to iTerms do
  begin
    sSeries := sSeries + IntToStr(iPrev) + ' ';
    iNext   := iPrev + iCurr;      // build the new term first
    iPrev   := iCurr;              // then slide both values along
    iCurr   := iNext;
  end;
  lblOut.Caption := sSeries;       // 0 1 1 2 3 5 8 13 21 34
end;
PassTerm added (iPrev)iNextiPrev afteriCurr after
10111
21212
31323
42535

Read pass 3 as an example: iPrev is 1 and iCurr is 2, so 1 is added to the text, iNext := 1 + 2 gives 3, and the slide makes iPrev = 2 and iCurr = 3.

Order matters when you slide

If you overwrite iPrev or iCurr before iNext has been worked out, an old value is lost for good. It is the same idea as swapping two variables with a temporary one: always save a value before you replace it.

Greatest Common Divisor (GCD) and Lowest Common Multiple (LCM)

The GCD of two numbers is the largest number that divides exactly into both. Euclid’s method finds it with remainders: divide the first number by the second and keep the remainder, then let the second number become the first and the remainder become the second. Repeat until the remainder is 0. The last non-zero divisor is the GCD. We don’t know in advance how many repeats are needed, so a while loop is the right choice.

Delphi — GCD by Euclid, then LCM
var
  iFirst, iSecond, iA, iB, iRemainder, iGCD, iLCM : Integer;
begin
  iFirst  := StrToInt(edtFirst.Text);        // e.g. 84
  iSecond := StrToInt(edtSecond.Text);       // e.g. 36

  iA := iFirst;                              // work on copies so the originals survive
  iB := iSecond;
  while iB <> 0 do
  begin
    iRemainder := iA mod iB;
    iA := iB;
    iB := iRemainder;
  end;
  iGCD := iA;                                // the last non-zero divisor

  iLCM := (iFirst div iGCD) * iSecond;
end;
PassiAiBiA MOD iB
1843612
236120
stop120— iB is 0, loop ends

So GCD(84, 36) = 12. The LCM is the smallest number that both numbers divide into exactly. It follows from the GCD: LCM = (first DIV GCD) × second, so (84 DIV 12) × 36 = 7 × 36 = 252. Check: 252 ÷ 84 = 3 and 252 ÷ 36 = 7, both exact.

Divide first, then multiply

Doing the DIV before the multiplication keeps the intermediate number small, which helps avoid overflow with large values, and because the GCD divides exactly into the first number the DIV loses nothing.

Converting Decimal to Binary, Octal or Hexadecimal

To write a decimal number in another base, repeatedly divide by that base. Each time, the remainder (MOD) is the next digit — working from the right-hand end of the answer — and the quotient (DIV) is what remains to be converted. Stop when the quotient reaches 0.

Two small tricks make the code short:

A repeat loop is used so that the number 0 still produces one digit ('0').

Delphi — decimal to base 2, 8 or 16
const
  sDigits = '0123456789ABCDEF';
var
  iNumber, iWork, iBase, iRemainder : Integer;
  sResult : string;
begin
  iNumber := StrToInt(edtNumber.Text);       // e.g. 77
  iBase   := 2;                             // change to 8 for octal or 16 for hexadecimal
  iWork   := iNumber;                        // the loop destroys iWork, so keep iNumber
  sResult := '';
  repeat
    iRemainder := iWork mod iBase;
    sResult    := sDigits[iRemainder + 1] + sResult;   // new digit goes in FRONT
    iWork      := iWork div iBase;
  until iWork = 0;
  lblOut.Caption := sResult;
end;

Tracing 77 in base 2:

PassiWork beforeiWork MOD 2sResult afteriWork after (DIV 2)
1771'1'38
2380'01'19
3191'101'9
491'1101'4
540'01101'2
620'001101'1
711'1001101'0 — stop

So 77 is 1001101 in binary. With iBase := 8 the same loop gives 115 (77 = 1 × 64 + 1 × 8 + 5), and with iBase := 16 it gives 4D, because the remainder 13 picks the letter D from the lookup string.

Converting Binary or Octal to Decimal

Going the other way, every digit has a place value of base ^ exponent. Work from the right: the last digit has exponent 0, the next one exponent 1, and so on. Multiply each digit by its place value and add everything up. The Power function (from the Math unit) does the raising to a power.

Delphi — binary or octal text to decimal
var
  sText : string;
  i, iDigit, iExp, iBase : Integer;
  rDecimal : Real;
begin
  sText    := edtValue.Text;                 // e.g. '110101'
  iBase    := 2;                            // use 8 for octal text such as '247'
  rDecimal := 0;
  iExp     := 0;
  for i := Length(sText) downto 1 do      // right to left
  begin
    iDigit   := StrToInt(sText[i]);
    rDecimal := rDecimal + iDigit * Power(iBase, iExp);
    Inc(iExp);
  end;
  lblOut.Caption := FloatToStrF(rDecimal, ffFixed, 8, 0);   // 53
end;

Tracing 110101 in base 2, from the right:

DigitiExpPower(2, iExp)Digit × place valueRunning total
10111
01201
12445
03805
14161621
15323253

So 110101 in binary is 53. Setting iBase := 8 and entering 247 gives 2 × 64 + 4 × 8 + 7 = 167.

An alternative way to get the digit

Instead of StrToInt(sText[i]) you can write Ord(sText[i]) - Ord('0'). The characters '0' to '9' are stored one after the other in the ASCII table, so subtracting the code for '0' leaves the digit’s own value.

Converting Hexadecimal to Decimal

Hexadecimal works exactly the same way, with base 16 — but some of its digits are letters. A to F stand for 10 to 15, and StrToInt cannot read letters, so each character must first be turned into its value. A case statement does this neatly: digits '0' to '9' go through StrToInt, and each letter is listed with its value.

Delphi — hexadecimal to decimal using CASE
var
  sHex : string;
  rDecimal : Real;
  iPos, iValue, iExp : Integer;
  cChar : Char;
begin
  sHex     := InputBox('Hexadecimal', 'Enter a hex value:', '1C5');
  rDecimal := 0;
  iExp     := 0;
  for iPos := Length(sHex) downto 1 do
  begin
    cChar := UpCase(sHex[iPos]);             // accept 'c' as well as 'C'
    case cChar of
      '0'..'9' : iValue := StrToInt(cChar);
      'A' : iValue := 10;
      'B' : iValue := 11;
      'C' : iValue := 12;
      'D' : iValue := 13;
      'E' : iValue := 14;
      'F' : iValue := 15;
    end;
    rDecimal := rDecimal + iValue * Power(16, iExp);
    Inc(iExp);
  end;
  ShowMessage(FloatToStrF(rDecimal, ffFixed, 8, 0));   // 453
end;

For 1C5: the 5 has exponent 0 (5 × 1 = 5), the C is 12 with exponent 1 (12 × 16 = 192), and the 1 has exponent 2 (1 × 256 = 256). Total: 5 + 192 + 256 = 453.

Alternative — letting Ord do the work

Instead of listing six letters, use the fact that 'A' to 'F' are consecutive in the ASCII table. The distance of a letter from 'A' is Ord(c) - Ord('A'), and since A is worth 10 you simply add 10. For 'C' that is 67 − 65 + 10 = 12.

Delphi — the same conversion using Ord with grouped CASE ranges
for iPos := Length(sHex) downto 1 do
begin
  case UpCase(sHex[iPos]) of
    '0'..'9' : iValue := Ord(sHex[iPos]) - Ord('0');
    'A'..'F' : iValue := Ord(UpCase(sHex[iPos])) - Ord('A') + 10;
  end;
  rDecimal := rDecimal + iValue * Power(16, iExp);
  Inc(iExp);
end;
Trap — the right-to-left order

The exponent must start at 0 on the last character. If you loop from the front (for iPos := 1 to Length(sHex)) with the exponent starting at 0, every digit gets the wrong place value. Either loop with downto, as above, or start the exponent at Length(sHex) - 1 and count down.

Which Loop for Which Algorithm?

AlgorithmLoop usedWhy
Factors, prime test, perfect number, factorial, FibonacciforThe number of repeats is known: 1 to n, or a chosen number of terms.
GCD (Euclid)whileNobody knows how many remainders are needed; it might even be zero if the second number is 0.
Decimal to another baserepeatUnknown number of divisions, but at least one digit must be produced, even for 0.
Binary, octal or hexadecimal to decimalfor … downtoOne pass per character, from the last one to the first.
Grade 10 · Practical

String Manipulation Grade 10

Strings are sequences of characters. Delphi provides built-in functions and procedures to analyse, extract, and modify strings.

What is String Manipulation?

String manipulation is the process of working with text inside a program — searching it, pulling pieces out of it, changing it and measuring it. A string is simply a piece of text: a name, an ID number, an email address or a whole sentence are all strings.

Everyday analogy: Think of a string like a row of bead letters on a piece of string, exactly like a beaded keyring that spells a name. Each bead is one character and it sits in a fixed position. String manipulation is what you do when you slide beads off the end, count how many there are, swap a small to a capital bead, or read which bead is sitting in position 3.

WHY IT MATTERS

Almost every real program handles text. When you log in, the computer compares the string you typed against the stored one. When a website greets you by your first name only, it has extracted that name out of your full name. When a form checks that an email contains an "@", it is searching a string. Learning these functions means you can validate input, format output neatly, and pull useful data out of messy text — skills you will use in every program from here on.

Note: In Delphi, the very first character of a string sits at position 1 (not 0). This is why the reference string below numbers its letters starting at 1.

Reference String

All examples on this page use: sSourceText := 'Andre is cute';

Positions: A=1, n=2, d=3, r=4, e=5, (space)=6, i=7, s=8, (space)=9, c=10, u=11, t=12, e=13

Quick Reference

NameTypeWhat it doesReturns
PosFunctionPosition of a substring in a stringInteger
Index [ ]—Character at a specific positionString (1 char)
CopyFunctionExtract part of a stringString
InsertProcedureInsert text into a stringModifies original
DeleteProcedureRemove part of a stringModifies original
LengthFunctionNumber of characters in a stringInteger
UpperCaseFunctionConvert to all capitalsString
LowerCaseFunctionConvert to all lowercaseString
T2Term 2 · Basic String Methods (Length, UpperCase)

Length — String Length

Syntax
IntegerVariable := Length(SourceText);
Delphi
iX := Length(sSourceText);   // = 13 (length of 'Andre is cute')
iX := Length('Hello');       // = 5

Group 4 — Changing Case

Changing case means turning all the letters into capitals (UpperCase) or all into small letters (LowerCase). The most important reason we do this is to compare text fairly. The computer thinks 'YES', 'yes' and 'Yes' are three different strings, so if you force them all to lowercase first, they all match.

Everyday analogy: Imagine a teacher marking a one-word answer. Whether a learner wrote "Cape Town", "CAPE TOWN" or "cape town", it is the same correct answer. Lowercasing both the answer and the memo before comparing is how you make sure capitals do not unfairly mark someone wrong.

Important Rule: UpperCase and LowerCase return a new string — they do not change the original unless you store the result back into a variable.

UpperCase and LowerCase

Delphi
sResult := UpperCase(sSourceText);
// 'Andre is cute' → 'ANDRE IS CUTE'

sResult := LowerCase(sSourceText);
// 'Andre is cute' → 'andre is cute'
T3Term 3 · Full String Methods & First Principles

Group 1 — Searching a String

Searching means asking "is this smaller piece of text in there, and if so, where?" The answer you get back is a position number. This is the first thing you do before you can extract or change part of a string, because you usually need to know where something is first.

Everyday analogy: It is like using Find (Ctrl+F) in a document. You type a word, and the computer jumps to the spot where it appears and tells you where it is. Pos is Delphi's version of that "Find".

Pos — Find Position

Returns the integer position of the first occurrence of a substring. Returns 0 if not found.

Syntax
IntegerVariable := Pos(StrToBeFound, SourceText);
Delphi
iX := Pos('e', sSourceText);    // = 5  (first 'e' in 'Andre')
iX := Pos('is', sSourceText);   // = 7
iX := Pos('xyz', sSourceText);  // = 0  (not found)

Index [ ] — Character at Position

Access a single character using square brackets and a position number.

Syntax
StringVariable := SourceText[CharacterPosition];
Delphi
sNewText := sSourceText[2];   // = 'n'
sNewText := sSourceText[5];   // = 'e'

Group 2 — Extracting Part of a String

Extracting means taking a copy of a piece of the string without changing the original. You decide where to start and how many characters to grab. This is how you pull a first name out of a full name, a year out of a date, or an area code out of a phone number.

Everyday analogy: Think of cutting a slice out of a loaf of bread. The loaf (the original string) stays whole; you just take a slice from a chosen spot of a chosen thickness. Copy takes the slice, and Index [ ] takes a single thin slice — just one character.

Copy — Extract Substring

Extracts a section of text starting at a position for a given number of characters.

Syntax
StringVariable := Copy(SourceText, BeginPosition, Length);
Delphi
sNewText := Copy(sSourceText, 10, 4);  // = 'cute'  (start at 10, take 4)
sNewText := Copy(sSourceText, 1, 5);  // = 'Andre' (start at 1, take 5)

Group 3 — Changing a String

Changing a string means actually modifying it — adding text in, taking text out, or measuring it. Unlike extracting, these Insert and Delete procedures change the original string directly, so afterwards the string is different from before.

Everyday analogy: This is like editing a sentence in your exercise book. Insert squeezes a new word into the middle of the sentence; Delete rubs a few words out. Length is just counting how many letters the sentence now has.

Insert — Add Text

Inserts text into an existing string at a given position. Modifies the string directly.

Syntax
Insert(InsertText, SourceText, Position);
Delphi
Insert('very ', sSourceText, 10);
// sSourceText is now: 'Andre is very cute'

Delete — Remove Text

Removes a section of text from a string. Modifies the string directly.

Syntax
Delete(SourceText, Position, Length);
Delphi
Delete(sSourceText, 9, 5);
// sSourceText is now: 'Andre is' (removed ' cute')

Practical Patterns

Reverse a String

Delphi
var
  sInput, sReverse: string;
  i: Integer;
begin
  sInput   := edtInput.Text;
  sReverse := '';
  for i := Length(sInput) downto 1 do
    sReverse := sReverse + sInput[i];
  lblResult.Caption := sReverse;
end;

Count Occurrences of a Character

Delphi — count vowels
var
  sText: string;
  i, iCount: Integer;
begin
  sText  := LowerCase(edtInput.Text);
  iCount := 0;
  for i := 1 to Length(sText) do
    if sText[i] IN ['a','e','i','o','u'] then
      Inc(iCount);
  lblResult.Caption := 'Vowels: ' + IntToStr(iCount);
end;

Extract First Name from "Surname, Name"

Delphi — using Pos and Copy
var
  sFullName, sName, sSurname: string;
  iCommaPos: Integer;
begin
  sFullName  := edtInput.Text;           // e.g. 'Smith, John'
  iCommaPos  := Pos(',', sFullName);
  sSurname   := Copy(sFullName, 1, iCommaPos - 1);
  sName      := Copy(sFullName, iCommaPos + 2, Length(sFullName));
  lblOut.Caption := 'Name: ' + sName + '  Surname: ' + sSurname;
end;

Count the Words in a Sentence (Even With Extra Spaces)

Counting the spaces and adding 1 only works when every word is separated by exactly one space. As soon as a learner types two spaces in a row, the answer is wrong. The reliable approach is to count the moments where a new word begins: a non-space character that arrives while you were not already inside a word. A Boolean flag, bInWord, remembers which state you are in.

Delphi — count words using an inWord flag
var
  sSentence: string;
  i, iWords: Integer;
  bInWord: Boolean;
begin
  sSentence := edtSentence.Text;     // e.g. 'Eskom  load   shedding is back'
  iWords  := 0;
  bInWord := False;
  for i := 1 to Length(sSentence) do
    if sSentence[i] = ' ' then
      bInWord := False               // a space ends any word we were in
    else if bInWord = False then   // a letter, and we were NOT in a word yet
    begin
      Inc(iWords);                   // a new word starts here
      bInWord := True;
    end;
  lblResult.Caption := 'Words: ' + IntToStr(iWords);   // 5
end;
Count transitions, not spaces

In 'Eskom load shedding is back' there are 7 spaces but only 5 words. The counter only goes up on the character where a word starts, so extra spaces never matter.

Remove Characters by Building a New String

You cannot "pull" a character out of the middle of a string with a loop easily, and you should not Delete inside a for loop (the positions shift under you). The safe pattern is to start with an empty result string, look at every character of the original, and append only the characters you want to keep.

Delphi — remove all digits (keep everything else)
var
  sText, sClean: string;
  i: Integer;
begin
  sText  := 'Bo2k3aap7';
  sClean := '';
  for i := 1 to Length(sText) do
    if not (sText[i] IN ['0'..'9']) then
      sClean := sClean + sText[i];
  // sClean = 'Bokaap'
end;
Delphi — keep only letters and digits (remove symbols)
sClean := '';
for i := 1 to Length(sText) do
  if sText[i] IN ['A'..'Z', 'a'..'z', '0'..'9'] then
    sClean := sClean + sText[i];
// 'Sipho#12!_Ngcobo'  becomes  'Sipho12Ngcobo'
Delphi — remove every space
sClean := '';
for i := 1 to Length(sText) do
  if sText[i] <> ' ' then
    sClean := sClean + sText[i];
// '082 555 1234'  becomes  '0825551234'

All three versions share the same skeleton; only the if condition changes. Notice the character ranges: 'A'..'Z' means "every character from A to Z" and only works inside a set.

Extract Each Word (Tokens) With Pos, Copy and Delete

To split a sentence into its words, keep finding the next space, copy everything in front of it, then Delete that piece (and the space) from a working copy so the next word moves to the front. Two details make it work:

Delphi — list every word in a memo
var
  sWork, sToken: string;
  iSpace: Integer;
begin
  sWork := edtSentence.Text + ' ';     // e.g. 'Pap en  vleis  op Sondag'
  memOut.Clear;
  iSpace := Pos(' ', sWork);
  while iSpace > 0 do
  begin
    sToken := Copy(sWork, 1, iSpace - 1);   // the text before the space
    if sToken <> '' then                      // skip empty tokens
      memOut.Lines.Add(sToken);
    Delete(sWork, 1, iSpace);              // remove the token AND its space
    iSpace := Pos(' ', sWork);              // find the next space
  end;
end;

The same pattern splits on any separator. For comma-separated data, append ',' instead of a space and search for ','. Because the loop destroys sWork, the original text in edtSentence stays untouched.

Pick a Random Word From a Sentence

A common trick is to choose a random space, throw away everything up to and including it, and then take the word that now sits at the front. Assume the sentence has single spaces and ends with a full stop.

  1. Pick a random position between 1 and the length. Repeat until the character at that position is a space.
  2. Delete from position 1 up to and including that space.
  3. Find the next space with Pos. If there is one, copy the characters before it.
  4. If there is no further space, you picked the last space: copy what is left, except the final full stop.
Delphi — random word after a random space
var
  sRest, sPick: string;
  iPlace, iSpace: Integer;
begin
  Randomize;                                 // once, e.g. in FormCreate
  sRest := 'Table Mountain is covered in cloud.';
  repeat
    iPlace := Random(Length(sRest)) + 1;   // Random(n) gives 0..n-1, so add 1
  until sRest[iPlace] = ' ';
  Delete(sRest, 1, iPlace);                // remove everything up to the chosen space
  iSpace := Pos(' ', sRest);
  if iSpace > 0 then
    sPick := Copy(sRest, 1, iSpace - 1)
  else
    sPick := Copy(sRest, 1, Length(sRest) - 1);   // last word: drop the full stop
  lblWord.Caption := sPick;
end;
TRAP: Random(n) never returns n

Random(Length(sRest)) gives a number from 0 to Length - 1. Position 0 does not exist in a string, so always add 1 to land in the range 1..Length. Also remember that the repeat loop would never finish if the sentence contained no spaces at all.

Palindrome Test

A palindrome reads the same forwards and backwards (for example RACECAR). Build the reverse with a downto loop, then compare the two strings with =. This assumes the text has already been normalised: all the same case and no spaces or punctuation (use UpperCase and the remove-spaces pattern above first).

Delphi — is it a palindrome?
var
  sWord, sBack: string;
  i: Integer;
  bPalindrome: Boolean;
begin
  sWord := 'RACECAR';
  sBack := '';
  for i := Length(sWord) downto 1 do
    sBack := sBack + sWord[i];
  bPalindrome := (sWord = sBack);     // True for RACECAR, False for KAROO
end;

Replace Characters In Place

Because a string is a row of characters you can number, you can overwrite one character by assigning to its position. Replacing keeps the length the same, whereas Insert makes the string longer.

Delphi — replace every hyphen with a space
var
  sPhone: string;
  i: Integer;
begin
  sPhone := '021-555-0147';
  for i := 1 to Length(sPhone) do
    if sPhone[i] = '-' then
      sPhone[i] := ' ';
  // sPhone = '021 555 0147'  (still 12 characters)
end;
Replace vs Insert

sPhone[4] := ' ' overwrites the character at position 4. Insert(' ', sPhone, 4) squeezes a new space in and pushes the rest to the right, so the string grows by one. Copy the text into a string variable first; you cannot assign to one character of edtPhone.Text directly.

Test Membership With IN

IN asks "is this single character one of the members of this set?" The result is Boolean, so it is perfect inside an if. A set can list characters, or use a range such as '0'..'9'.

Delphi — IN with a set
bVowel := cLetter IN ['A','E','I','O','U'];
if sCode[1] IN ['0'..'9'] then
  ShowMessage('Starts with a digit');
TRAP: IN is not a substring search

IN only tests one character against a set of characters. It cannot tell you whether the text 'Pty' appears inside a company name. To search for a piece of text, use Pos and check whether the answer is greater than 0: if Pos('Pty', sName) > 0 then ...

Worked Example — Reading a South African ID Number

A South African ID number is a 13-digit string that packs several pieces of information into fixed positions — a favourite exam question because it uses Length, Copy and the index [ ] all at once.

PositionsMeaningExample (8801235111088)
1–2Year of birth (YY)88
3–4Month (MM)01
5–6Day (DD)23
7–10Gender sequence (5000+ = male)5111 → Male
11Citizenship (0 = SA citizen, 1 = resident)0
12Historically a race indicator; on modern IDs it is always 8 and carries no meaning8
13Check digit (Luhn algorithm)8
Delphi — extract information from an ID
var
  sID, sDOB, sGender, sStatus : string;
  iSeq : Integer;
begin
  sID := edtID.Text;

  // 1. Validate — an ID must be exactly 13 characters long
  if Length(sID) <> 13 then
  begin
    ShowMessage('An ID number must be exactly 13 digits.');
    Exit;
  end;

  // 2. Date of birth — YY at 1, MM at 3, DD at 5 (rebuild as DD/MM/YY)
  sDOB := Copy(sID, 5, 2) + '/' + Copy(sID, 3, 2) + '/' + Copy(sID, 1, 2);

  // 3. Gender — the 4 digits at positions 7-10; 5000 and up = male
  iSeq := StrToInt(Copy(sID, 7, 4));
  if iSeq >= 5000 then
    sGender := 'Male'
  else
    sGender := 'Female';

  // 4. Citizenship — the single character at position 11
  if sID[11] = '0' then
    sStatus := 'SA citizen'
  else
    sStatus := 'Permanent resident';

  // 5. Show the result
  memOut.Lines.Add('Date of birth: ' + sDOB);
  memOut.Lines.Add('Gender: ' + sGender);
  memOut.Lines.Add('Status: ' + sStatus);
end;
The check digit (Grade 11/12 extension)

The 13th digit is a check digit worked out from the other 12 using the Luhn algorithm. A program can recalculate it and compare — if it does not match, the ID was mistyped. That step adds a loop and some arithmetic on top of the string work shown here.

Grade 10 · Term Planner

Grade 10 — Year Planner Grade 10

Based on the 2026 IT CAPS Annual Teaching Plan. Practical (Paper 1) and Theory (Paper 2) topics per term.

A year planner — not a test scope

This shows when each topic is taught during the year — it is not a list of what any single test covers. Any work done so far this year, plus the foundational work from earlier grades, can still be assessed, so don't study only the current term's topics.

T4
Term 4 • October – November (PAT due + exams)
Internet services, PAT file I/O & revision
🔬 Practical (Paper 1)
Grade 10 · Exam Resources

Exam Extras Out-of-CAPS

These topics are not explicitly required by CAPS but have appeared in NSC past papers (2015–2024). Knowing them can mean the difference between a pass and a distinction.

How to use this page

Items marked P1 appear in Paper 1 (practical/Delphi), P2 in Paper 2 (theory), and Both in either paper. These are supplementary — master your CAPS content first.

The Software Development Process

CAPS never teaches "how to plan a whole program" as one topic — instead it hands you the individual planning tools (IPO tables, TOE charts, pseudocode) at different points across Grade 10 and 11. Strung together in order, those tools form a complete process for turning a vague idea into a finished, working program. None of this is examinable on its own, but following it will make your PAT — and any open-ended practical question — far less overwhelming.

  1. Pin down exactly what the program must do. A one-line description ("a till program") is not enough to start coding from — write out every input the program will receive, every calculation or decision it must make, and every output it must produce. This is the same information an IPO table asks for (Grade 10 T1, Algorithms & Problem Solving), just applied to the whole program instead of one calculation.
  2. Sketch the interface before placing a single component. Decide which forms the user will see, what components sit on each one, and how the user moves between them. Keep the same layout, colours and button placement on every form — a program that looks different from screen to screen feels unfinished even when the code is solid.
  3. Map out which event triggers which task. For every button, checkbox or form event, list precisely what must happen when it fires — this is exactly what a TOE (Task–Object–Event) chart is for (also covered on the Algorithms & Problem Solving page). Doing this before writing code stops the common mistake of half-remembering what a button was supposed to do halfway through typing its handler.
  4. Break the plan into procedures and functions before typing the body of any of them. Decide which pieces of logic will repeat, which need a return value and which don't, and what needs to pass between them as parameters — this is where the Procedures & Functions (Grade 11 T2) content and the local-vs-global variable rules on that page earn their keep.
  5. Write the code in small, testable pieces rather than the whole program at once — build and run after every procedure or two so that when something breaks, you know it's in the last few lines you typed, not buried somewhere in 200 lines you haven't tested yet.
  6. Test with data designed to break it, not just data that works. Run the program with an empty text box, a negative number, the largest and smallest values it should accept, and anything else a careless user might type — this is the mindset behind the Input Validation content (Grade 10 T2). Where something goes wrong before you can even see the output, Delphi's debugger (breakpoints, F8 stepping, the Watch List — see Data Types & Variables) will show you exactly which line is responsible.
Why bother with all of this for a PAT?

A PAT is marked over months, revisited many times, and often built on by a partner or by future-you after a long break. Time spent planning up front — even just a page of notes on what each form does — is what makes it possible to pick the project back up in Term 4 and still understand your own Term 2 code.

Practical Extras — Paper 1 (Delphi)

These Delphi functions, components and techniques are not listed in CAPS but appear regularly in exam questions or are needed to solve exam problems efficiently.

P1

StringReplace()

Replaces all or first occurrence of a substring within a string.
s := StringReplace(s, 'old', 'new', [rfReplaceAll]);

P1

Format() function

Formats numbers/strings with precise control — Format('%.2f', [rVal]) gives 2 decimal places. More powerful than FloatToStrF.

P1

Random() & Randomize()

Generate random integers. Always call Randomize; first to seed the generator. Random(100) returns 0–99.

P1

TOpenDialog / TSaveDialog

Let users browse for files at runtime.
if OpenDialog1.Execute then sFile := OpenDialog1.FileName;

P1

DateToStr() & StrToDate()

Convert between TDate values and string representation. Used with TDateTimePicker.
sDate := DateToStr(dtpDate.Date);

P1

Try…Except…End (Exception Handling)

Catch runtime errors gracefully — e.g. invalid StrToInt input.
try iNum := StrToInt(edtNum.Text); except ShowMessage('Invalid'); end;

P1

Memo.Lines.Count

Returns the number of lines in a Memo. Often used in loops to process all memo lines.
for i := 0 to Memo1.Lines.Count - 1 do

P1

SameText() / CompareText()

Case-insensitive string comparison — avoids problems when user types 'yes', 'YES' or 'Yes'.
if SameText(sInput, 'yes') then

P1

IntToHex() & HexToInt()

Convert integers to hexadecimal strings and back. Sometimes tested in conjunction with number systems theory.
sHex := IntToHex(255, 4); // = '00FF'

P1

Odd() & Even() functions

Built-in boolean checks — cleaner than MOD 2.
if Odd(iNum) then // true if iNum is odd

P1

Break & Continue in loops

Break stops the rest of the loop from processing. Continue skips the rest of the current pass and moves on to the next iteration. Both appear in exam solutions — know the difference. (Break vs Exit is taught on the Loops page.)

Theory Extras — Paper 2

These theory topics have appeared in NSC Theory papers but sit at the edge of or outside the formal CAPS scope. They typically appear in social implications or "current technology" questions.

P2

Artificial Intelligence (AI) & Machine Learning

AI appears regularly in social implications questions — automation of jobs, AI decision-making, bias in AI, chatbots. Not deeply technical — understand the concept and its social effects.

P2

Blockchain Technology

A distributed digital ledger of linked blocks. Used in cryptocurrency, supply chain, and secure records. Appeared in Gr12 theory papers. Know: what it is, how it works, and 2 uses.

P2

Deep Fakes

AI-generated fake videos or audio that appear authentic. Social implications question topic — impacts on trust, truth, and politics. Know the definition and two risks.

P2

Dark Web

A part of the internet not indexed by search engines, accessed via special software (Tor). Used for anonymity — legal and illegal uses. Appeared in theory cybercrime questions.

P2

Net Neutrality

The principle that all internet traffic should be treated equally — ISPs cannot throttle or prioritise certain content. A social/political IT topic.

P2

IPv6

The successor to IPv4 — uses 128-bit addresses (vs 32-bit) to solve address exhaustion. Format: 2001:0db8:85a3::8a2e:0370:7334. Know why it was introduced.

P2

RAID Levels (0, 1, 5)

RAID 0: speed (striping, no redundancy). RAID 1: mirroring (exact copy). RAID 5: striping with parity (balance of speed + fault tolerance). CAPS only mentions RAID in general — exams go deeper.

P2

Steganography

Hiding secret information within ordinary files (images, audio) without detection. Different from encryption — encryption scrambles data; steganography hides its existence. Appeared in theory questions.

P2

Smart Contracts

Self-executing contracts where terms are written in code on a blockchain. No middlemen needed. Related to blockchain technology — appeared in Gr12 social implications.

P2

Edge Computing

Processing data close to where it is generated (the "edge" of the network) rather than sending it all to a central cloud server. Reduces latency — important for IoT and 5G.

P2

Bus Network Topology

All devices share a single communication line (the bus). Not in the current CAPS but appeared in older papers. Advantage: cheap. Disadvantage: single point of failure; performance drops with more devices.

P2

Mesh Network Topology

Each device connects to several others, so data has more than one possible path. Not in the current CAPS (it sits under "network innovation"). Advantage: very reliable — traffic reroutes if a link fails. Disadvantage: expensive, many connections needed. It's how "mesh Wi-Fi" systems work.

P2

Social Engineering

Manipulating people (rather than systems) to reveal confidential information. Includes pretexting, baiting, tailgating. Appears in cybercrime theory questions.

Both

Number System Conversions

Exams frequently ask you to convert values — not just explain systems. Practise: decimal↔binary, decimal↔hex, binary↔hex. Know the place values (powers of 2 and 16).

P2

POPIA (Protection of Personal Information Act)

South African law governing how personal data must be collected, stored, and protected. Appears in privacy and legal implications questions. Know: what it is, who it protects, and 2 requirements.

P2

Cybercrimes Act (2020)

SA legislation that criminalises hacking, ransomware, online fraud, and malicious communications. Often referenced in cybercrime theory questions for Gr12.

P2

Digital Twins

A virtual replica of a physical object or system, updated in real time from sensor data. Used in engineering, manufacturing, and smart cities. Appeared in 4IR/IoT questions.

Complete Delphi Functions Quick Reference

A comprehensive reference of all Delphi functions you need to know — both CAPS-required and commonly appearing in exams.

String Functions

Function/ProcedureWhat it doesExample
Length(s)Returns number of charactersLength('Hello') = 5
Pos(find, source)Position of substring (0 if not found)Pos('lo','Hello') = 4
Copy(source, start, len)Extract substringCopy('Hello',2,3) = 'ell'
Insert(text, var s, pos)Insert text into string at positionInsert('!','Hello',6) → 'Hello!'
Delete(var s, pos, len)Remove characters from stringDelete(s,1,3)
UpperCase(s)All uppercaseUpperCase('hi') = 'HI'
LowerCase(s)All lowercaseLowerCase('HI') = 'hi'
Trim(s)Remove leading/trailing spacesTrim(' Hi ') = 'Hi'
StringReplace(s,old,new,flags)Replace substring(s)StringReplace(s,'a','e',[rfReplaceAll])
SameText(s1,s2)Case-insensitive comparison (boolean)SameText('Yes','yes') = True
Concat(s1,s2)Join two strings (same as +)Concat('Hel','lo')
s[i]Character at index i (1-based)s[1] = first character

Math Functions

FunctionWhat it doesExample
Sqr(x)x squared (x²)Sqr(4) = 16
Sqrt(x)Square rootSqrt(16) = 4
Power(base, exp)base to the power of expPower(2,8) = 256
Round(x)Round to nearest integerRound(4.6) = 5
Trunc(x)Remove decimal (truncate toward zero)Trunc(4.9) = 4
Ceil(x)Round UP to integerCeil(4.1) = 5
Floor(x)Round DOWN to integerFloor(4.9) = 4
Abs(x)Absolute valueAbs(-5) = 5
Random(n)Random integer 0 to n-1Random(6)+1 simulates a die
RandomizeSeed the random generator (call once)Call before Random()
Inc(x) / Inc(x,n)Increment by 1 or nInc(i) ≡ i := i+1
Dec(x) / Dec(x,n)Decrement by 1 or nDec(i,3) ≡ i := i-3
Odd(n)True if n is oddOdd(3) = True
PiReturns π (3.14159…)rArea := Pi * Sqr(r)

Type Conversion Functions

FunctionConvertsExample
StrToInt(s)String → IntegerStrToInt('42') = 42
StrToFloat(s)String → RealStrToFloat('3.14')
StrToIntDef(s, default)String → Integer (safe — returns default if invalid)StrToIntDef(edtNum.Text, 0)
IntToStr(n)Integer → StringIntToStr(42) = '42'
FloatToStr(r)Real → StringFloatToStr(3.14)
FloatToStrF(r, fmt, digits, dec)Formatted real → StringFloatToStrF(r, ffFixed, 6, 2)
Ord(c)Char → Integer (ASCII value)Ord('A') = 65
Chr(n)Integer → CharChr(65) = 'A'
UpCase(c)Single char to uppercaseUpCase('a') = 'A'
IntToHex(n, digits)Integer → Hex stringIntToHex(255,2) = 'FF'
DateToStr(d)TDate → StringDateToStr(Now)
FormatFloat(fmt, r)Real → formatted stringFormatFloat('#,##0.00', 1234.5)

Past Paper Patterns & Tips

Paper 1 (Practical) — What Always Appears

SectionWhat to expectCommon traps
Q1: General programmingStrings, loops, decisions, calculations (~30–40 marks)Off-by-one errors in loops; forgetting to initialise variables
Q2: Arrays & files1D/2D arrays, text file reading/writing (~20–25 marks)Using wrong index (0 vs 1-based); not closing file
Q3: OOPClass with constructor, accessors, mutators, toString (~25–30 marks)Calling Create on the object var (not class name); forgetting Result in functions
Q4: Database/SQLTADOQuery, SQL statements including JOIN (~20–25 marks)Not calling qry.Close before changing SQL; wrong JOIN ON condition
Recursion (Gr12)Write a recursive function; trace it (~10–15 marks)Missing base case; not returning Result

Paper 2 (Theory) — What Always Appears

TopicTypical mark allocationWhat examiners look for
Hardware & software15–20 marksSpecific advantages/disadvantages; real-world examples
Networks & internet20–25 marksCorrect terminology; topology advantages/disadvantages
Databases & normalisation20–30 marksCorrect normal form identification; proper primary/foreign key use
Social implications20–25 marksBalance of positive AND negative effects; specific examples
Cybercrime10–15 marks (Gr12)Correct crime type names; effects on both victim and business
Current technology (IoT, AI, VR)10–15 marks (Gr12)Practical application examples; social implications

General Exam Advice

Top 5 mark-saving habits
  • Read the question twice — and write your Paper 2 answers in sentences or short paragraphs, never bullet points, whatever the command word is. Markers only credit the first few bullets, but they must read a whole paragraph
  • Never leave a practical question blank — partial marks are awarded for correct structure
  • In SQL: always check your WHERE condition matches the question's criteria exactly
  • In OOP: write the constructor first — it sets up all the attributes you'll use elsewhere
  • In theory: "advantage AND disadvantage" means you need both for full marks