A pencil-and-paper workbook: save data in files, build your own helpers, understand life online, then show what you know.
Variables forget everything the moment a program closes. A text file remembers. You will learn the few commands that connect to a file, read it, write to it and close it, and how to stop your program crashing when the file is missing.
var tFile : TextFile; // logical name: a variable in the program begin AssignFile(tFile, 'Sales.txt'); // link it to the physical name on the disk // from here on the commands use tFile, never the physical name
| Command | What it does |
|---|---|
| AssignFile(tFile, 'Data.txt') | Links the logical name to the physical name. Always first. |
| Reset(tFile) | Opens an existing file for reading, at line 1. |
| Rewrite(tFile) | Creates a new, empty file for writing. If the file exists, everything in it is erased. |
| Append(tFile) | Opens an existing file for writing at the end. Old lines are kept. |
| ReadLn(tFile, sLine) | Reads one line into sLine and moves on to the next line. |
| WriteLn(tFile, sText) | Writes sText to the file as one new line. |
| EOF(tFile) | True when there is nothing left to read. |
| CloseFile(tFile) | Saves and closes the file. Never forget it. |
| FileExists('Data.txt') | True if that file is on the disk. Takes the physical name. |
// READ every line
AssignFile(tFile, 'Names.txt');
Reset(tFile);
while not EOF(tFile) do
begin
ReadLn(tFile, sLine); // one line per pass
memOut.Lines.Add(sLine);
end;
CloseFile(tFile);
// ADD a line, or create the file the first time
AssignFile(tFile, 'Sales.txt');
if FileExists('Sales.txt') then
Append(tFile)
else
Rewrite(tFile);
WriteLn(tFile, edtItem.Text + ',' + edtPrice.Text);
CloseFile(tFile);// Method 1: ask first
if FileExists('Names.txt') then
...
else
ShowMessage('Names.txt was not found');
// Method 2: try..except
AssignFile(tFile, 'Names.txt');
try
Reset(tFile); // error here if the file is missing
... // read the lines
CloseFile(tFile);
except
on E: EInOutError do
ShowMessage('Could not read Names.txt');
end;Circle the command that opens the file correctly for the job.
| 1 | Show every learner name from Names.txt in a memo. | Reset Rewrite Append |
| 2 | At the start of each term, start a fresh Attendance.txt and throw away the old one. | Reset Rewrite Append |
| 3 | Add a new sale to the bottom of Sales.txt without losing the earlier sales. | Reset Rewrite Append |
| 4 | Save the very first high score, when the file does not exist yet. | Reset Rewrite Append |
| 5 | Add a late-comer to the end of Latecomers.txt. | Reset Rewrite Append |
Missing.txt does not exist. Write exactly what memOut shows after this code has run.
AssignFile(tFile, 'Missing.txt');
memOut.Lines.Add('Start');
try
Reset(tFile);
memOut.Lines.Add('Opened');
CloseFile(tFile);
except
memOut.Lines.Add('Problem');
end;
memOut.Lines.Add('Finish');Queue.txt holds four lines: Zinhle, Thabo, Aisha and Pieter. Complete a row for every check of the loop; the values are those after the body has run. The last row is the check that stops the loop, so the values stay the same.
sInitials := ''; iCount := 0; AssignFile(tFile, 'Queue.txt'); Reset(tFile); while not EOF(tFile) do begin ReadLn(tFile, sLine); Inc(iCount); sInitials := sInitials + Copy(sLine, 1, 1); end; CloseFile(tFile);
| Check | EOF(tFile) | sLine | iCount | sInitials |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
This code should add up the numbers in Stock.txt (one whole number per line) and show the total. It never stops and may crash. Find three errors and write the corrections.
AssignFile(tFile, 'Stock.txt'); Reset(tFile); iTotal := 0; while not EOF(tFile) do begin iTotal := iTotal + StrToInt(sLine); end; lblTotal.Caption := IntToStr(iTotal);
Names.txt holds one learner name per line. Write code that shows every name in memOut with its number in front (1. Zinhle) and shows 5 names (the real count) in lblCount. If the file does not exist, show the message Names.txt was not found. Variables tFile, sLine and iCount are declared.
The item is typed in edtItem and its price in edtPrice. Write code that adds one line such as Pie,12 to the end of Sales.txt, keeping all earlier sales. If Sales.txt does not exist yet, it must be created.
Real programs read a whole file into arrays, work with the data, and write a neat report back out. In this unit you practise the full journey: read, split, store, process, report.
Write each piece from Stock.txt in the correct pile.
| Slip number | Item pile | Price pile (R) | Quantity pile |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 |
const
MAX = 50;
var
arrItem : array[1..MAX] of String;
arrPrice : array[1..MAX] of Integer;
arrQty : array[1..MAX] of Integer;
iCount : Integer; // how many items were really read
// ----- in the event handler
iCount := 0;
AssignFile(tFile, 'Stock.txt');
Reset(tFile);
while (not EOF(tFile)) and (iCount < MAX) do
begin
ReadLn(tFile, sLine); // e.g. 'Sugar,32,10'
Inc(iCount); // the next free place
iPos := Pos(',', sLine);
arrItem[iCount] := Copy(sLine, 1, iPos - 1);
Delete(sLine, 1, iPos); // '32,10' is left
iPos := Pos(',', sLine);
arrPrice[iCount] := StrToInt(Copy(sLine, 1, iPos - 1));
Delete(sLine, 1, iPos); // '10' is left
arrQty[iCount] := StrToInt(sLine);
end;
CloseFile(tFile);AssignFile(tOut, 'Report.txt'); Rewrite(tOut); WriteLn(tOut, 'TUCK SHOP STOCK'); // heading: once for i := 1 to iCount do // body: repeats WriteLn(tOut, arrItem[i] + ': R' + IntToStr(arrPrice[i])); WriteLn(tOut, 'Items: ' + IntToStr(iCount)); // summary: once CloseFile(tOut);
Trace the seven numbered statements for the line Sugar,32,10. After each statement write the value of iPos, what sLine holds, and the value stored in an array (write a dash if nothing is stored).
sLine := 'Sugar,32,10';
iPos := Pos(',', sLine); // 1
arrItem[4] := Copy(sLine, 1, iPos - 1); // 2
Delete(sLine, 1, iPos); // 3
iPos := Pos(',', sLine); // 4
arrPrice[4] := StrToInt(Copy(sLine, 1, iPos - 1)); // 5
Delete(sLine, 1, iPos); // 6
arrQty[4] := StrToInt(sLine); // 7| Statement | iPos | sLine afterwards | Value stored |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | |||
| 6 | |||
| 7 |
Menu.txt has lines such as Pie,12. This code should read it into arrItem (String) and arrPrice (Integer). Find four errors.
iCount := 0;
AssignFile(tFile, 'Menu.txt');
Reset(tFile);
while not EOF(tFile) do
begin
ReadLn(tFile, sLine);
iPos := Pos(',', sLine);
arrItem[iCount] := Copy(sLine, 1, iPos);
Delete(sLine, 1, iPos);
arrPrice[iCount] := sLine;
Inc(iCount);
end;Fares.txt has one route on each line in the form Route,Fare,Seats (for example Bellville,22,15). The arrays arrRoute (String), arrFare and arrSeats (Integer) and the variables below are declared. Write the statements that replace the comment, so that every line is split into the three arrays.
iCount := 0; AssignFile(tFile, 'Fares.txt'); Reset(tFile); while (not EOF(tFile)) and (iCount < MAX) do begin ReadLn(tFile, sLine); // your statements go here end; CloseFile(tFile);
The arrays arrItem, arrPrice and arrQty and the counter iCount are already filled. Write code that creates StockReport.txt in this form. The value of an item is its price times its quantity; the last line holds the total of all the values.
StockReport.txt (first, second and last line)TUCK SHOP STOCK
Bread: R18 x 12 = R216
...
Total stock value: R1183
As programs grow, one long block of code becomes hard to read and to fix. A procedure is a named helper: write the steps once, then call its name whenever you need them. You will also learn how to hand a helper some information, and who is allowed to see which variable.
type
TForm1 = class(TForm)
...
private
procedure ShowBanner; // declaration
...
implementation
procedure TForm1.ShowBanner; // definition
begin
memOut.Lines.Add('*****************');
memOut.Lines.Add(' KASI TUCK SHOP');
memOut.Lines.Add('*****************');
end;
procedure TForm1.btnStartClick(Sender: TObject);
begin
ShowBanner; // call
memOut.Lines.Add('Open 7:00 to 16:00');
ShowBanner; // call again
end;procedure TForm1.ShowLine(sItem: String; iPrice: Integer); // 2 parameters
begin
memOut.Lines.Add(sItem + ': R' + IntToStr(iPrice));
end;
// calls: the values in the brackets are the arguments
ShowLine('Bread', 18);
ShowLine(arrItem[3], arrPrice[3]); // arguments can be expressionsvar Form1 : TForm1; iTotal : Integer; // global: all procedures can use it procedure TForm1.AddToTotal(iAmount: Integer); var iDouble : Integer; // local: only exists in here begin iDouble := iAmount * 2; iTotal := iTotal + iDouble; // changes the global end;
This code should show the average of 240 and 8 in lblAvg using a procedure. Find three errors.
procedure TForm1.ShowAverage(iTotal, iCount); var rAvg : Real; begin rAvg := iTotal / iCount; lblAvg.Caption := FloatToStrF(rAvg, ffFixed, 8, 1); end; // in the button (iTotal holds 240, iCount holds 8) ShowAverage(iTotal); lblNote.Caption := FloatToStr(rAvg);
iTotal is global and starts at 0. Each call adds the price plus a 10% service fee (whole rands only) to the total. Complete a row for each call. The last row is for the final statement.
procedure TForm1.Sell(sItem: String; iPrice: Integer);
var
iFee : Integer;
begin
iFee := iPrice div 10;
iTotal := iTotal + iPrice + iFee;
memOut.Lines.Add(sItem + ' R' + IntToStr(iPrice + iFee));
end;
// in the button
iTotal := 0;
Sell('Airtime', 50);
Sell('Chips', 12);
Sell('Pie', 25);
memOut.Lines.Add('Total R' + IntToStr(iTotal));| Call | iPrice | iFee (local) | Line added to memOut | iTotal after |
|---|---|---|---|---|
| Sell('Airtime', 50) | ||||
| Sell('Chips', 12) | ||||
| Sell('Pie', 25) | ||||
| Last statement |
Write a procedure ShowTable with one value parameter, iNumber (Integer), that displays that number's times table from 1 to 12 in memTable (for example 3 x 7 = 21). Then write the button code that calls it for 7 and for 12. You do not need to write the declaration in the private section.
A procedure does a job. A function does a job and hands a value back, like an assistant who comes back from the shelf with the price. Functions let you calculate or check something in one place and use the answer anywhere, and they are the best tool for checking that what a user typed is valid.
| Number in | 1 | 2 | 5 | 0 | 10 |
|---|---|---|---|---|---|
| Number out | 4 | 7 | 16 | 1 | 31 |
function TForm1.CalcVat(rPrice: Real): Real; // one parameter, returns a Real
begin
Result := rPrice * 0.15;
end;
function TForm1.RollDie: Integer; // no parameters
begin
Result := Random(6) + 1;
end;
// using them
rVat := CalcVat(200); // 30
lblVat.Caption := FloatToStrF(CalcVat(StrToFloat(edtPrice.Text)), ffFixed, 8, 2);
iRoll := RollDie; // no brackets
if RollDie = 6 then
ShowMessage('A six!');Work out what each call returns. Here is the function:
function TForm1.Level(iMark: Integer): Integer; begin if iMark >= 80 then Result := 7 else if iMark >= 70 then Result := 6 else if iMark >= 60 then Result := 5 else if iMark >= 50 then Result := 4 else if iMark >= 40 then Result := 3 else if iMark >= 30 then Result := 2 else Result := 1; end;
| Call | Result |
|---|---|
| Level(85) | |
| Level(64) | |
| Level(50) | |
| Level(49) | |
| Level(12) |
function TForm1.IsValidMark(iMark: Integer): Boolean;
begin
Result := (iMark >= 0) and (iMark <= 100); // range check
end;
function TForm1.IsValidCell(sCell: String): Boolean;
var
i : Integer;
begin
Result := (Length(sCell) = 10) and (Copy(sCell, 1, 1) = '0'); // length and format
for i := 1 to Length(sCell) do
if not (sCell[i] in ['0'..'9']) then // type check
Result := False;
end;
// keep asking until the answer is valid
repeat
sCell := InputBox('Cell number', 'Enter 10 digits starting with 0:', '');
until IsValidCell(sCell);Circle the better choice for each task.
| 1 | Show a welcome banner in a memo. | Procedure Function |
| 2 | Calculate the price of an item including VAT. | Procedure Function |
| 3 | Check whether a cell number is valid. | Procedure Function |
| 4 | Clear all the edit boxes on the form. | Procedure Function |
| 5 | Work out the average of the marks in an array. | Procedure Function |
| 6 | Display the times table of a number. | Procedure Function |
Find four errors in this code. The program should show the average of 240 and 8 and a pass/fail decision.
function TForm1.IsPass(iMark : Integer) : Boolean;
begin
if iMark >= 50 then
Result := True;
end;
function TForm1.CalcAverage(iTotal, iCount : Integer) : Integer;
begin
Result := iTotal / iCount;
end;
// in the button
CalcAverage(240, 8);
lblAvg.Caption := IntToStr(rAvg);A PIN is valid only if it has exactly 4 characters and they are all digits. Write a Boolean function IsValidPin(sPin: String). Then write the code for the button that keeps asking for a PIN with an InputBox until a valid one is entered.
Paper 2 asks you to explain, compare and discuss. In this unit you meet the ways we communicate online, the technology in your pocket and the ideas that keep data safe. You also practise answering in paragraphs: a marker reads a whole paragraph, but may stop crediting a list after the first few bullets.
Long before computers, people hid messages by moving every letter a fixed number of places along the alphabet. In the message below every letter was moved 3 places forward (A became D, B became E and so on). Move each letter 3 places back to read it. Then hide your own word: write TAXI with every letter moved 5 places forward.
Four friends share a notebook that records who paid whom, one page per payment. To make cheating hard every page also shows a fingerprint: the last two digits of (the amount + 3 × the fingerprint of the page before). Page 1 uses 0 as the fingerprint of the page before. Work out the fingerprint of every page. (Example: page 2 = last two digits of 20 + 3 × 50 = 170, so the fingerprint is 70.) Then a cheat secretly changes the amount on page 2 from R20 to R80: recalculate the fingerprints of all four pages with the same rule.
| Page | Amount (R) | Fingerprint | Cheat: amount now (R) | Cheat: new fingerprint |
|---|---|---|---|---|
| 1 | 50 | 50 | ||
| 2 | 20 | 80 | ||
| 3 | 75 | 75 | ||
| 4 | 40 | 40 |
The friends each keep a copy of the notebook. In two or three sentences, explain how the fingerprints show that page 2 was changed, and why it is so much work for a cheat to hide it.
| Form | What it is | Good to know |
|---|---|---|
| Microblogging | Very short public posts shared with followers (for example on X) | Quick news that is easy to reshare |
| SMS | A short text sent over the cellular network | Needs no internet; banks use it for one-time PINs |
| Instant messaging | Real-time chat, voice notes and pictures over the internet, one-to-one or in groups (WhatsApp) | Free over data or Wi-Fi; informal |
| Social media | Websites and apps where people make profiles, share and interact (Facebook, Instagram, TikTok) | Huge audience; privacy and digital footprint risks |
| Form | What it is | Good to know |
|---|---|---|
| Videocasting | A video series published on a channel such as YouTube, recorded or live | Viewers choose when to watch |
| Podcasting | An audio series you subscribe to and download | Can be played offline |
| VoIP | Voice (and video) calls carried over the internet instead of the phone network | Free between users of the same app; needs a stable connection, enough bandwidth and low delay (latency) |
| Video conferencing | A live meeting where several people see and hear each other (Teams, Meet, Zoom) | Shows facial expressions; uses a lot of data |
| Technology | What it does | Remember |
|---|---|---|
| GPS | A receiver works out its position from the signals of satellites | Powers navigation and e-hailing apps; it only listens, it does not send |
| Bluetooth | A short-range wireless link between two devices | About 10 m: earphones, speakers, a car's hands-free kit |
| Wi-Fi | A wireless link to a network and the internet through a router | Tens of metres: home, school, office |
| Access point | A device that connects Wi-Fi devices to the wired network | A school uses many so that every classroom has a signal |
| 4G / 5G | Mobile internet through the cellular towers of a network provider | Works across the country; 5G is faster and has less delay |
| Protocol | Its job |
|---|---|
| SMTP | Sends e-mail from your program to the mail server and on to the receiver's server |
| POP3 | Downloads e-mail to one device, normally removing it from the server |
| IMAP | Lets you read e-mail while it stays on the server, so every device shows the same mailbox |
| VoIP | Carries a voice call as data across the internet |
| HTTPS | Fetches web pages with encryption (the padlock) |
Write the term from the word bank next to its description.
Word bank: access point · Bluetooth · GPS · IMAP · microblogging · podcasting · POP3 · SMS · SMTP · VoIP
| Description | Term |
|---|---|
| Needs no internet; sent over the cellular network | |
| Very short public posts that followers can read and reshare | |
| An audio series you subscribe to and can play offline | |
| Voice calls carried over the internet | |
| Sends an e-mail from your program to the mail server | |
| Downloads e-mail to one device, normally removing it from the server | |
| Keeps e-mail on the server so that your phone and laptop show the same mailbox | |
| Works out a position from the signals of satellites | |
| A short-range wireless link between a phone and earphones | |
| Connects Wi-Fi devices to the wired network |
Zinhle's provider lets her video calls run smoothly even when her brother downloads large games, but after she has used 20 GB it slows her whole line. Name the practice in each case and explain the difference in a short paragraph.
Explain what encryption is, and how it protects the photos on a phone that has been stolen.
Thandi uses the password thandi2008 for her e-mail, her banking app and her social media. In a paragraph, explain why this is risky and how multi-layer (multi-factor) verification would make her banking app safer.
Explain what a blockchain is, and why it is very hard to change an old record on it.
Mr Dube drives for an e-hailing app and has no other job. Discuss two advantages and two disadvantages of this kind of work for him. Write full sentences.
Next term you will use databases in Delphi. This unit is the paper-based preparation: what a database and a DBMS are, why a DBMS beats a paper register or a text file, the different kinds of database, and the people who work with them.
| LearnerNo | Surname | Name | Grade | Cell |
|---|---|---|---|---|
| 1001 | Mokoena | Thabo | 11 | 082 555 0101 |
| 1002 | Naidoo | Priya | 10 | 083 555 0102 |
| 1003 | Botha | Jan | 11 | 084 555 0103 |
| 1004 | Dlamini | Zinhle | 12 | 072 555 0104 |
| 1005 | Khumalo | Sipho | 11 | 073 555 0105 |
| 1006 | Pillay | Aisha | 10 | 074 555 0106 |
Circle the type of database that fits best.
| 1 | A teacher keeps her marks in an Access database on her own laptop. | Desktop Server Distributed |
| 2 | All the teachers and the school office use one admin system that is stored on the school's server. | Desktop Server Distributed |
| 3 | A bank keeps copies of its customer records in Johannesburg, Durban and Cape Town, and the copies keep one another up to date. | Desktop Server Distributed |
| 4 | The spaza shop owner keeps a small stock database on the shop's only computer. | Desktop Server Distributed |
Write the term from the word bank next to the situation.
Word bank: backup · database administrator · database analyst · database programmer · multi-user access · querying · security · validation
| Situation | Term |
|---|---|
| A learner's mark of 150 is rejected. | |
| Only the office staff can change fees; teachers may only view them. | |
| The disk crashes at night, but the data is restored the next morning. | |
| Ten teachers capture marks at the same time without overwriting one another. | |
| The principal asks for all Grade 11 learners who owe fees and the answer appears in seconds. | |
| Designs the tables and how they are linked. | |
| Makes sure backups are made and only authorised users can log in. | |
| Writes the queries and code that let an app read and update the data. |
This term you stored data in text files. Think about searching, checking the data, several users and security. Explain, in a paragraph, why a school should use a DBMS rather than text files to keep the records of 1 200 learners.
Design the table tblProduct for the tuck shop. On the grid draw a table with five field names as headings, circle the primary key and fill in three records of sample data.
No notes, no computer. Show all your working. Write Delphi code neatly and use correct indentation.
Quiz.txt holds four lines:
Quiz.txtThabo,14
Aisha,9
Lwazi,17
Mpho,12
Complete a row for every check of the loop. The last row is the check that ends the loop.
iCount := 0;
iPass := 0;
AssignFile(tFile, 'Quiz.txt');
Reset(tFile);
while not EOF(tFile) do
begin
ReadLn(tFile, sLine);
Inc(iCount);
iPos := Pos(',', sLine);
arrName[iCount] := Copy(sLine, 1, iPos - 1);
arrMark[iCount] := StrToInt(Copy(sLine, iPos + 1, Length(sLine)));
if arrMark[iCount] >= 12 then
Inc(iPass);
end;
CloseFile(tFile);| Check | EOF(tFile) | iCount | arrMark[iCount] | iPass |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
iGlobal is a global variable. Write exactly what memOut shows.
procedure TForm1.Boost(iScore: Integer);
begin
iScore := iScore * 2;
iGlobal := iGlobal + iScore;
end;
// in the button
iGlobal := 0;
iMark := 10;
Boost(iMark);
Boost(iMark + 3);
memOut.Lines.Add('iMark = ' + IntToStr(iMark));
memOut.Lines.Add('iGlobal = ' + IntToStr(iGlobal));This code should add the name typed in edtName as a new line at the end of the existing file Visitors.txt, keeping the old lines. Find and correct three errors.
AssignFile(tFile, 'Visitors.txt');
Rewrite(tFile);
WriteLn(edtName.Text);
CloseFile(tFile)
ShowMessage('Saved');This function should return True when an age is from 14 to 19 (inclusive), and the button should use it. Find and correct three errors.
function TForm1.IsValidAge(iAge : Integer) : Boolean;
begin
if (iAge >= 14) or (iAge <= 19) then
Result := True;
end;
procedure TForm1.btnCheckClick(Sender: TObject);
var
iAge : Integer;
begin
iAge := StrToInt(edtAge.Text);
if IsValidAge then
ShowMessage('Age accepted')
else
ShowMessage('Age must be 14 to 19');
end;Choose the word from the word bank for each description.
Word bank: access point · Bluetooth · GPS · IMAP · SMTP
| Description | Answer |
|---|---|
| The protocol that sends e-mail | |
| Keeps e-mail on the server so that every device shows the same mailbox | |
| A short-range link between a phone and earphones | |
| Works out a position from satellite signals | |
| Connects Wi-Fi devices to the wired network |
Differentiate between shaping and throttling.
Explain how encryption and multi-layer verification each help to protect an online bank account. Write in sentences.
Explain what a blockchain is and why it is difficult to change an old record on it.
Define a DBMS and describe two of its functions.
Results.txt has one learner on each line in the form Name,Mark (for example Nomsa,72). The constant MAX = 50 and the global arrays arrName (String), arrMark (Integer) and the global counter iCount are declared. (In all the code questions MAX, arrName, arrMark and iCount are declared as global; declare any other variables that you use.) Write a procedure LoadResults with no parameters that reads the file into the arrays and sets iCount. If the file does not exist it must show Results.txt not found.
Write a function CalcAverage with no parameters that returns, as a Real, the average of the marks in arrMark (positions 1 to iCount). If iCount is 0 it must return 0. (For the marks 72, 45, 88, 50, 63 the answer is 63.6.)
Write a procedure ShowAbove with one value parameter, iLimit (Integer), that displays in memOut the name and mark of every learner whose mark is greater than iLimit, in the form Sizwe: 88. Then write the button line that calls it with the limit 60.
The arrays and iCount are filled. Write code that creates ResultsReport.txt. The first line is the heading, then one line for each learner in the form Nomsa: 72 PASS (50 or more is a PASS, otherwise FAIL), and a last line that shows how many learners passed, such as Passed: 4.
ResultsReport.txtRESULTS REPORT
Nomsa: 72 PASS
Pieter: 45 FAIL
...
Passed: 4
A password is valid only if it has at least 8 characters and contains at least one digit. Write a Boolean function IsValidPassword with one String parameter sPass.