Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pascal

How to declare a procedure in Pascal

Kainat Asif

Procedures in Pascal are declared using the procedure keyword, as shown in the code snippet below:

procedure _procName_ (_parameter(s)_: _parameterType_;, _parameter(s)_: _parameterType_;, ...); 
_localDeclarations_
begin
   //procedure body
end;
  • _procName_: The name of the procedure.
  • _argument(s)_: The arguments that are passed to the procedure.
  • _parameterType_: The data type of the arguments passed.
  • _localDeclarations_: Declarations such as variables, constants, functions, etc. that are referred to in the procedure body.

Examples

Example 1

Consider a simple example of a procedure that calculates the sum of two numbers:

program Example1;
var
   a, b, calSum : integer;
   
procedure sum(a, b: integer; var calSum: integer);
var
   tempSum: integer;//local Declaration

begin
   calSum := a + b;
end;

begin
   a := 5;
   b := 10;
   sum(a, b, calSum);
   writeln(a, ' + ', b, ' = ', calSum);
end.

Explanation

  • Lines 5-11: The sum() procedure is declared that takes three parameters, a, b, and calSum. The sum() procedure calculates the mathematical sum of a and b in line 10 and stores the sum in a variable parameter, calSum. As calSum is a variable parameter, changing its value in the procedure will be propagated back to the main block. So, we can store the sum in calSum and access the sum in main.
  • Line 16: The sum() procedure is called in line 16 and is passed with a, b, and calSum as parameters.

Example 2

Consider an example of a procedure with no parameters:

program Example2;
   
procedure noParam();
begin
   writeln('This is a procedure with no parameters');
end;

begin
   noParam();
end.

RELATED TAGS

pascal

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring