Grade 11 · Own methods & text files · Lesson and coding task · about 16 minutes
Open this task in the Delphi workspace →
Until now you have only used procedures and functions. Time to write your own. They live above the event handlers that call them.
A function calculates and returns one value through Result:
function TotalCost(rPrice : Real; iQty : Integer) : Real;
begin
Result := rPrice * iQty;
end;
A procedure just does something — no return value:
procedure Heading(sTitle : String);
begin
memOutput.Lines.Add(sTitle);
memOutput.Lines.Add('----------');
end;
Calling them reads like English: rTot := TotalCost(12.50, 4); and Heading('Till slip');. The values you pass in are parameters — each with its own type in the header.
TotalCost := rPrice * iQty;. Both work here; Result is the modern habit.Your task: a till slip
Write the two routines above, then use both in the button click to print a neat till slip.
What you will do
- Write function TotalCost(rPrice : Real; iQty : Integer) : Real
- Write procedure Heading(sTitle : String) that prints the title plus a ---------- line
- The click handler calls Heading('Till slip') and then shows: Total: R 50.00
Hints
- The function header ends with : Real; and its body is one line: Result := rPrice * iQty;
- Heading is a procedure — it returns nothing, it just Adds two lines.
- In the handler: call Heading first, then rTot := TotalCost(StrToFloat(edtPrice.Text), StrToInt(edtQty.Text));
Model solution
function TotalCost(rPrice : Real; iQty : Integer) : Real;
begin
Result := rPrice * iQty;
end;
procedure Heading(sTitle : String);
begin
memOutput.Lines.Add(sTitle);
memOutput.Lines.Add('----------');
end;
procedure TfrmShop.btnTotalClick(Sender: TObject);
var
rTot : Real;
begin
Heading('Till slip');
rTot := TotalCost(StrToFloat(edtPrice.Text), StrToInt(edtQty.Text));
memOutput.Lines.Add('Total: R ' + FloatToStrF(rTot, ffFixed, 10, 2));
end;