So what is recursion ?When a function calls itself, it is called a recursive function. Some problems by nature are recursive.
Lets take the case of
Fibonacci numbers, it's a series of where every number is the sum of the preceding two numbers. The first and second numbers of the series are 0 and 1 respectively by definition since they do not have two preceding numbers.
Thus the series looks like:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
We can define the n
th term of the fibonacci series by,
t
0 = 0
t
1 = 1
t
n = t
n-1 + t
n-2Now suppose we need to calculate the 15th term i.e. t
15 of the series.
How would you go about ?
Now,
t
15 = t
14 + t
13To calculate t
15 we need the values of t
14 and t
13.
Similarly, to calculate t
13 we need the values of t
12 and t
11Hence, you can see each term of the fibonacci series is defined by the preceding two fibonacci numbers; and again each of the two preceding numbers is defined by their respective predecessors.
This is a called recursive definition.
In a hypothetical language, we can write a function to calculate the nth of the series as:
function Fibonacci(n: Integer)
if (n = 0) return 0 //first term is zero
else if (n = 1) return 1 //Second term is 1
else return Fibonacci(n-1) + Fibonacci(n-2)
end
The first two if statements are called base cases. Without them the function would call itself endlessly. In every recursive problem we need base cases to prevent an infinite loop.
Hope this explanation clears thing up a bit