Recursion is a programming technique where a method calls itself to solve a problem. Recursive solutions involve breaking a problem into smaller, similar subproblems, often with a base case to stop the recursion.
Recursive solutions can be elegant and concise but may consume more memory. Iterative solutions use loops and can be more efficient in terms of memory usage.
Recursive function examples:
Recursion is a powerful programming technique in Java (and other programming languages) where a method calls itself to solve a problem. It is a fundamental concept in computer science and can be applied to various scenarios. Here's an explanation of recursion in Java with examples.
Key Concepts:
public class Factorial { public int factorial(int n) { // Base case: factorial of 0 or 1 is 1 if (n == 0 || n == 1) { return 1; } // Recursive case: n! = n * (n-1)! else { return n * factorial(n - 1); } } public static void main(String[] args) { Factorial fact = new Factorial(); int result = fact.factorial(5); System.out.println("Factorial of 5 is: " + result); } }
public class Fibonacci { public int fibonacci(int n) { // Base cases: Fibonacci of 0 and 1 is the number itself if (n <= 1) { return n; } // Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2) else { return fibonacci(n - 1) + fibonacci(n - 2); } } public static void main(String[] args) { Fibonacci fib = new Fibonacci(); int result = fib.fibonacci(7); System.out.println("Fibonacci number at position 7 is: " + result); } }
Recursion is a powerful technique for solving problems that can be broken down into smaller, similar subproblems. It often leads to elegant and concise code but should be used with caution to avoid stack overflow errors when handling large inputs.