Recursion is a programming technique that can accomplish a lot with a little bit of code. Because recursive procedures call themselves, their operation seems like magic. Here are a couple of recursive functions - one to calculate factorials and one to calculate Fibonacci numbers.
Example 1: Factorials
N factorial for a positive integer N is defined as the product of the integers 1 through N. It is usually written as N!.
Function factorial(N:integer):Integer;
Begin
If N=1 then result:=1
else result:=N*factorial(N-1);
end;
Example 2: Fibonacci Numbers
Fibonacci numbers are members of an infinite series of integers in which the first two numbers are 1, and each number after the 2nd is the sum of the two preceding numbers (1, 1, 2, 3, 5, 8, 13....). Here's a function that returns the Nth Fibonacci number:
Function Fibonacci(n:integer) :integer;
Begin
If N<=2 then result:=1
else result:=Fibonacci(n-1)+Fibonacci(n-2);
end;
Here is a program that calculates integer powers of a real number. Recursion is one of 4 techniques tested. The program will also introduce you to techniques for accurately measuring program run times. Click here to download source code for IntPowerDemo.