B public static void main(String[]args) { sayHello(5); } // a recursive method will always have a condition public static void sayHello(int num) { if (num == 0) System.out.println("Hello and Bye!"); else { System.out.println("Hello"); sayHello(num-1); // recursive } }
C public static void main(String[]args) { printNumbers(10); } // a recursive method will always have a condition public static void printNumbers(int num) { if (num == 0) System.out.println(num); else { System.out.println(num); printNumbers(num-1); // recursive System.out.println(num); } }
• Each time a recursive method is called, a new copy of the method runs, with new instances of parameters and local variables being created • As each copy finishes executing, it returns to the copy of the method that called it • When the initial copy finishes executing, it returns to the part of the program that made the initial call to the method
of Recursion • Direct recursion: a method calls itself • Indirect recursion: method A calls method B, and method B calls methodA. Or, method A calls method B, which calls ..., which calls method A
Factorial Method The natural definition of some problems leads to a recursive solution • The factorial of a nonnegative integer n is the product of all positive integers less or equal to n • Factorial of n is n * (n-1) * ... * 2 x 1 • The factorial of 0 is 1
Factorial Method // Factorial of n can be expressed in terms of // the factorial of n-1 // 0 ! =1 // n ! = n x (n-1) ! public static int factorial(int n) { if (n == 0) return 1; else return n*factorial(n-1); }
Fibonacci Numbers The natural definition of some problems leads to a recursive solution • The Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... • After the starting 0, 1, each term is the sum of the two preceding terms • Recursive solution: fib(n) = fib(n – 1) + fib(n – 2); • Base cases: fib(0) =0, fib(1) =1