public class RecursiveMethods { // // factorial(n) // // This is a recursive implementation // to find the factorial of an integer n. // // Note the base case is implied by // the assignment of the return variable. // public static int factorial( int n ) { int fact = 1; if ( n >= 2 ) fact = n * factorial(n-1); return( fact ); } // // countN() A recursive method to count the number // of times the integer n appears in the array. // // Note that the method is initially passed the length // of the array-1 as the sarting index and uses that // parameter to determine if the recursion should continue. // // public static int countN( int[] arr, int index, int n ) { int count = 0; if ( arr != null && index >= 0 ) { if ( arr[index] == n ) count = countN( arr, index-1, n ) + 1; else count = countN( arr, index-1, n ); } return( count ); } // // findMin() // // This method uses recursion to find the minimum // value in an array. // // note that the explicit base case is handled inside // the conditional statement. // public static int findMin( int[] arr, int index ) { int min = -1; if ( arr != null && index >= 0 ) { // The explicit base case is when we hae recursed // back to the first element in the array. if (index == 0) min = arr[0]; else // The recursive case returns the minimum of // the element at the current index and the // element returned from the recursive call. // min = Math.min(arr[index], findMin(arr, index-1)); } return( min ); } public static void main( String s[] ) { int[] a = { 3,2,2,0,2,3,2,4,2,5,7,9 }; System.out.println( countN(a, a.length-1, 9) ); System.out.println( findMin(a, a.length-1) ); } }