Lesson 13 · 13 of 20
Procedures · Pascal
Group named blocks of code into Pascal procedures, with parameters and local variables, to print a bakery receipt.

A procedure is a named block of code that you write once and call as often as you need. It is declared before the main begin, with `procedure`, its name and, in brackets, its parameters.
PrintLine(width: Integer; symbol: Char) takes two pieces of data: how many characters to draw and which one. It is called as PrintLine(26, '=') and PrintLine(26, '-'): the same code draws two different lines. In the declaration, parameters are separated by semicolons; in the call, by commas.
i is a local variable: it is declared in the procedure's own var block and only exists while the procedure runs. Another procedure can have its own i without the two getting mixed up.
PrintItem prints one line of the receipt and works out the amount, qty * price, without the main program having to know how. Greet welcomes each customer. The main program stays short and reads like a list of steps.
In the Lazarus desktop apps that DMarlon Studio builds, every button click calls a procedure just like these: its event handler.
Code · main.pas
program main;// A procedure is a named block of code that you can call again and again.procedure PrintLine(width: Integer; symbol: Char);var i: Integer; // a local variable: it only exists insidebegin for i := 1 to width do Write(symbol); WriteLn;end;procedure PrintItem(name: String; qty: Integer; price: Double);begin WriteLn(name:8, qty:3, ' x', price:6:2, qty * price:8:2);end;procedure Greet(customer: String);begin WriteLn('Welcome, ', customer, '!');end;begin Greet('Marta'); PrintLine(26, '='); PrintItem('Bread', 2, 1.20); PrintItem('Milk', 3, 0.95); PrintItem('Cheese', 1, 4.50); PrintLine(26, '-'); Greet('Luis');end.Output · fpc main.pas && ./main
Welcome, Marta!
==========================
Bread 2 x 1.20 2.40
Milk 3 x 0.95 2.85
Cheese 1 x 4.50 4.50
--------------------------
Welcome, Luis!Key points
procedure Name(parameters);declares a procedure.- Call it by name, with the values in brackets.
- Variables in its
varblock are local. - A procedure saves you from repeating the same code.
Exercise
Write a PrintTotal(amount: Double) procedure that prints the total line aligned with the amounts, and call it at the end with 9.75.