Recursion in Pascal
Our example demonstrates recursive functions in Pascal. Here’s a classic example of factorial calculation using recursion.
This Fact
function calls itself until it reaches the base case of Fact(0)
.
In the begin
block, we call our recursive functions and print their results.
Pascal doesn’t have closures like some modern languages, so we’ve implemented the Fibonacci function as a regular recursive function instead.
To run this program, save it as recursion.pas
and compile it using a Pascal compiler like Free Pascal:
The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).
Recursive functions can be powerful but should be used carefully, as deep recursion can lead to stack overflow errors. In many cases, an iterative solution might be more efficient.