Recursion is where a function invokes itself. Various algorithms utilize recursion, hence it's important to know this concept.
Always remember when creating a recursive function that you need 2 parts: the base case, and the recursive case. The recursive case is when the function calls itself. The base case is when the function doesn’t call itself again (this prevents the function go into an infinite loop)
Sample Code
In this example, we try to find the factorial of 5
public class Main {
public static void main(String[] args) {
// test the recursion method
Factorial f = new Factorial();
System.out.println(f.recursion(5));
}
}
class Factorial {
public long recursion(long n) {
// this is our base case
// always have a base case or else your recursion will never end
if (n <= 1) {
// here we are returning a value of 1
// in programming, this means the output is met or valid
return 1;
} else {
//recrusive case or also known as the method calling itself
return n * recursion(n - 1);
}
}
}
Note:
- Be careful with recursion as it can consume a lot of memory, and can create a program that never terminates. However, when used correctly recursion can be a very efficient and mathematically-elegant approach to programming.
- There’s no performance benefit to using recursion; in fact, loops are sometimes better for performance. Simply choose which is more important in your situation!
Top comments (0)