|
| 1 | +DSA using Java - Recursion |
| 2 | +Recursion refers to a technique in a programming language where a function calls itself. The function which calls itself is called a recursive method. |
| 3 | + |
| 4 | +Characteristics |
| 5 | +A recursive function must posses the following two characteristics |
| 6 | + |
| 7 | +Base Case(s) |
| 8 | + |
| 9 | +Set of rules which leads to base case after reducing the cases. |
| 10 | + |
| 11 | +Recursive Factorial |
| 12 | +Factorial is one of the classical example of recursion. Factorial is a non-negative number satisfying following conditions. |
| 13 | + |
| 14 | +0! = 1 |
| 15 | + |
| 16 | +1! = 1 |
| 17 | + |
| 18 | +n! = n * n-1! |
| 19 | + |
| 20 | +Factorial is represented by "!". Here Rule 1 and Rule 2 are base cases and Rule 3 are factorial rules. |
| 21 | + |
| 22 | +As an example, 3! = 3 x 2 x 1 = 6 |
| 23 | + |
| 24 | +private int factorial(int n){ |
| 25 | + //base case |
| 26 | + if(n == 0){ |
| 27 | + return 1; |
| 28 | + }else{ |
| 29 | + return n * factorial(n-1); |
| 30 | + } |
| 31 | +} |
| 32 | +Recursive Fibonacci Series |
| 33 | +Fibonacci Series is another classical example of recursion. Fibonacci series a series of integers satisfying following conditions. |
| 34 | + |
| 35 | +F0 = 0 |
| 36 | + |
| 37 | +F1 = 1 |
| 38 | + |
| 39 | +Fn = Fn-1 + Fn-2 |
| 40 | + |
| 41 | +Fibonacci is represented by "F". Here Rule 1 and Rule 2 are base cases and Rule 3 are fibonnacci rules. |
| 42 | + |
| 43 | +As an example, F5 = 0 1 1 2 3 |
| 44 | + |
| 45 | +Demo Program |
| 46 | +RecursionDemo.java |
| 47 | + |
| 48 | +package com.tutorialspoint.algorithm; |
| 49 | + |
| 50 | +public class RecursionDemo { |
| 51 | + public static void main(String[] args){ |
| 52 | + RecursionDemo recursionDemo = new RecursionDemo(); |
| 53 | + int n = 5; |
| 54 | + System.out.println("Factorial of " + n + ": " |
| 55 | + + recursionDemo.factorial(n)); |
| 56 | + System.out.print("Fibbonacci of " + n + ": "); |
| 57 | + for(int i=0;i<n;i++){ |
| 58 | + System.out.print(recursionDemo.fibbonacci(i) +" "); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + private int factorial(int n){ |
| 63 | + //base case |
| 64 | + if(n == 0){ |
| 65 | + return 1; |
| 66 | + }else{ |
| 67 | + return n * factorial(n-1); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + private int fibbonacci(int n){ |
| 72 | + if(n ==0){ |
| 73 | + return 0; |
| 74 | + } |
| 75 | + else if(n==1){ |
| 76 | + return 1; |
| 77 | + } |
| 78 | + else { |
| 79 | + return (fibbonacci(n-1) + fibbonacci(n-2)); |
| 80 | + } |
| 81 | + } |
| 82 | +} |
| 83 | +If we compile and run the above program then it would produce following result − |
| 84 | + |
| 85 | +Factorial of 5: 120 |
| 86 | +Fibbonacci of 5: 0 1 1 2 3 |
0 commit comments