Recursive Functions in Java

 

✅ Recursive Functions in Java

A recursive function is a method that calls itself to solve a problem.


🔹 Key Concepts

  1. Base Case – condition to stop recursion

  2. Recursive Case – where the method calls itself

🔁 Recursion breaks the problem into smaller subproblems until the base case is reached.


🔸 Example 1: Factorial of a Number

Problem: Calculate n! = n × (n-1) × (n-2) × ... × 1


public class Factorial { static int factorial(int n) { if (n == 0) // Base case return 1; else return n * factorial(n - 1); // Recursive call } public static void main(String[] args) { int result = factorial(5); System.out.println("Factorial of 5 is " + result); } }

Output:


Factorial of 5 is 120

🔸 Example 2: Fibonacci Series

Problem: Print nth Fibonacci number
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, ...


public class Fibonacci { static int fibonacci(int n) { if (n == 0) return 0; // Base case if (n == 1) return 1; // Base case return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case } public static void main(String[] args) { int n = 7; System.out.println("Fibonacci(" + n + ") = " + fibonacci(n)); } }

Output:


Fibonacci(7) = 13

🔸 Example 3: Sum of Digits

Problem: Find the sum of digits of a number using recursion


public class SumDigits { static int sumOfDigits(int n) { if (n == 0) return 0; return n % 10 + sumOfDigits(n / 10); } public static void main(String[] args) { int num = 1234; System.out.println("Sum of digits = " + sumOfDigits(num)); } }

Output:


Sum of digits = 10

🔹 When to Use Recursion?

Use recursion when:

  • The problem is naturally recursive (e.g., factorial, tree traversal)

  • The solution involves repeated subproblems

  • A loop would make the solution more complex


⚠️ Caution:

  • Recursive functions may cause StackOverflowError if the base case is missing or recursion is too deep.

  • Use iteration for efficiency when possible.

Comments

Popular posts from this blog

Object Oriented Programming PBCST 304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Object Oriented Programming PBCST 304 Course Details and Syllabus

Type casting in Java