Bailey Say

Recursion

Recursion is an important technique that can be used to solve certain problems in computer science. For example, what if you wanted to know the Fibonacci number at a certain index? Recursion can help.

How does recursion work?

Recursion occurs when a function calls itself as a part of its executables, meaning that it will be called numerous times when just calling it once. What does this look like? An easy example to show would be a method to find a certain number in the Fibonacci sequence:

public int fibonacciNumber(int termNumber) {

if (termNumber == 1) {

return 0;

} else if (termNumber == 2) {

return 1;

} else {

return this.fibonacciNumber(termNumber - 1) + this.fibonacciNumber(termNumber - 2);

}

}

Essentially, this function will try to find the value of a certain term in the Fibonacci sequence by adding its two previous values. This loops over and over again until reaching the first 2 numbers in the sequence, 0 and 1, which will be returned and make their way back up to the term number inputted by the user. Though this can be quite inefficient at larger amounts, it’s still a good example on how it can be implemented as a solution.