how to change code this into recursion Java? [closed]

public static long weightedSum(int[] a, int[] b, int n) {
    if (n == 0)
        return 0;
    else
        return a[n - 1] * b[n - 1] + weightedSum(a, b, n - 1);
}

Output :

int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 6, 7, 8, 9, 10 };

System.out.println(weightedSum(arr1, arr2, 1));  // output : 6
System.out.println(weightedSum(arr1, arr2, 2));  // output : 20
System.out.println(weightedSum(arr1, arr2, 3));  // output : 44
System.out.println(weightedSum(arr1, arr2, 4));  // output : 80
System.out.println(weightedSum(arr1, arr2, 5));  // output : 130

Leave a Comment