Parameters
The word subroutine can be used to refer to either a procedure or a function. Subroutines are more versatile when they have parameters to modify their processing. The parameters are used as variables within the subroutine.
The procedure in the following program has one parameter, NumberOfStars, of type integer. It is a local variable, which means that it can only be used inside the procedure. The argument 17 (the value of TitleLength) is supplied to it when the procedure is called. The variable Count, declared within the procedure, can only be used within the procedure and is another example of a local variable.
program DrawStars; {$APPTYPE CONSOLE} uses SysUtils; const Title = 'DrawStars Program'; var TitleLength : integer; procedure WriteStars(NumberOfStars: integer); var Count : integer; begin for Count := 1 to NumberOfStars do begin write('*'); end; writeln; end; begin TitleLength := length(Title); WriteStars(TitleLength); writeln(Title); WriteStars(TitleLength); readln; end.
The procedure can be made more versatile by introducing a second parameter of type char. In the next program the variables TitleLength and i are global variables, being available to the whole of the program, and NumberOfChars, Character and Count are local variables, being accessible only within the procedure. Read the code and work out roughly what the output should look like, then copy and paste the code into Lazarus or Delphi and see if you are correct.
procedure WriteChars(NumberOfChars: integer; Character : char); var Count : integer; begin for Count := 1 to NumberOfChars do begin write(Character); end; writeln; end; begin TitleLength := length(Title); WriteChars(TitleLength, '*'); writeln(Title); WriteChars(TitleLength, '*'); WriteChars(TitleLength, '_'); for i := TitleLength - 1 downto 1 do begin WriteChars(i, CHR(48+i)); end; readln; end.
- Syntax for writing a procedure
- How to call a procedure
- Parameters
- Arguments
- Local variables
- Use of the function length to determine the number of characters in a string