In: Computer Science
public int f8( int[] arr, int index ) { if ( index == -1 ) return 0; if (arr[index] == 2) return 1 + f8( arr, index - 1 ); return f8( arr, index - 1); }
ff8() is the tail recursive method
uses of tail recursion:
uses less memory and less stack frames.
import java.util.*;
class Hello {
public int f8(int[] arr, int index) {
if (index == -1)
return 0;
if (arr[index] == 2)
return 1 + f8(arr, index - 1);
return f8(arr, index - 1);
}
public int ff8(int[] arr, int index, int count) {
if (index == -1)
return count;
if (arr[index] == 2)
return ff8(arr, index - 1, count + 1);
return ff8(arr, index - 1, count);
}
public static void main(String[] args) {
int[] a = { 1, 2, 3, 2, 5 };
Hello h = new Hello();
System.out.println(h.f8(a, 4));
System.out.println(h.ff8(a, 4, 0));
}
}