Recursion in Ada
Ada supports recursive functions. Here’s a classic example.
In this Ada example, we define two recursive functions: Fact
for calculating factorials and Fib
for generating Fibonacci numbers.
The Fact
function is defined at the procedure level, while Fib
is defined locally within the main procedure body. Both functions demonstrate the use of recursion in Ada.
To run this program, save it as recursion.adb
and use the following commands:
Ada doesn’t have closures in the same way as some other languages, so we’ve represented the recursive Fibonacci function as a local function instead. This achieves a similar effect of having a locally scoped recursive function.
The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13), demonstrating that both recursive functions are working correctly.