Procedures and Functions in Pascal

July 23, 2024

Procedures and Functions in Pascal

In this post, we will explore the concept of procedures and functions in Pascal. These constructs allow you to create reusable blocks of code, making your programs more organized, efficient, and easier to maintain. Understanding how to define, call, and pass parameters to procedures and functions is essential for any Pascal programmer.

What are Procedures and Functions?

In Pascal, both procedures and functions are used to encapsulate code that performs a specific task. The main difference between the two is that a function returns a value, while a procedure does not.

Defining a Procedure

A procedure is defined using the procedure keyword, followed by the name of the procedure and a list of parameters (if any). Here’s a simple example:

procedure GreetUser(name: string);
begin
  writeln('Hello, ', name, '!');
end;

In this example, we have defined a procedure called GreetUser that takes one parameter, name, of type string. The procedure prints a greeting message to the console.

Calling a Procedure

To call a procedure, simply use its name followed by the required parameters. Here’s how you can call the GreetUser procedure:

begin
  GreetUser('Alice');
end;

This will output:

Hello, Alice!

Defining a Function

Functions are defined similarly to procedures, but they include a return type. Here’s an example of a function that adds two integers:

function AddNumbers(a, b: integer): integer;
begin
  AddNumbers := a + b;
end;

In this example, the function AddNumbers takes two parameters, a and b, and returns their sum as an integer.

Calling a Function

To call a function, you can use its name in an expression where its return value is needed. Here’s how you can call the AddNumbers function:

var
  result: integer;
begin
  result := AddNumbers(5, 10);
  writeln('The sum is: ', result);
end;

This will output:

The sum is: 15

Passing Parameters

Parameters can be passed to procedures and functions in two ways: by value and by reference. When passing by value, a copy of the variable is made, while passing by reference allows the procedure or function to modify the original variable.

To pass a parameter by reference, use the var keyword:

procedure Increment(var num: integer);
begin
  num := num + 1;
end;

When you call this procedure, any changes made to num will affect the original variable:

var
  number: integer;
begin
  number := 5;
  Increment(number);
  writeln('Number after increment: ', number);
end;

This will output:

Number after increment: 6

Conclusion

Procedures and functions are powerful tools in Pascal that help you create organized and reusable code. By understanding how to define, call, and pass parameters to them, you can write more efficient and maintainable programs. Practice creating your own procedures and functions, and soon you’ll find that they become an invaluable part of your coding toolkit!