CSci 4651 Problem set 6 source code for recursive functions.


public class TailRecursion {
    public static void main(String [] args) {
        int [] A = {3, 6, 7, 5, 4};
        int [] B = {3, 6, 5, 7, 9};
        System.out.println("sum_array(A,0) = " + sum_array(A,0));
        System.out.println("find(A,0,5) = " + find(A,0,5));
        System.out.println("find(A,0,2) = " + find(A,0,2));
        System.out.println("equal(A,B,0) = " + equal(A,B,0));
        System.out.println("equal(A,A,0) = " + equal(A,A,0));
        System.out.println("equal(A, new int[2],0) = " + equal(A, new int[2],0));
        System.out.println("to_string_reverse(A,0)" +  to_string_reverse(A,0));
   }

    public static int sum_array(int [] A, int i) {
        if (i < A.length) return (A[i] + sum_array(A, i+1));
        return 0;
    }

    public static boolean find(int [] A, int i, int x) {
        if (i >= A.length) return false;
        if (A[i] == x) return true;
        return find(A, i+1, x);
    }

    public static boolean equal(int[] A, int[] B, int i) {
        if (A.length == i && B.length == i) {
        	return true;
        }
        if (A.length == i || B.length == i) {
        	return false;
        }
        if (A[i] == B[i]) return equal(A, B, i+1);
        else return false;
    }

    public static String to_string_reverse(int [] A, int i) {
        if (i < A.length) {
            return to_string_reverse(A, i + 1) + " " + A[i];
        }
        return "";
    }
}

CSci 4651 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.