Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PROBLEM 1: Translate the following sum function from iterative to recursive. You

ID: 3781947 • Letter: P

Question

PROBLEM 1: Translate the following sum function from iterative to recursive. You should write a helper method. You may not use any "fields" to solve this problem (a field is a variable that is declared "outside" of the function declaration --- either before or after).

   */

   public static double sumI (double[] a) {

       double result = 0.0;

       int i = 0;

       while (i < a.length) {

           result = result + a[i];

           i = i + 1;

       }

       return result;

   }

   public static double sum (double[] a) {

       return 0; // TODO

   }

Explanation / Answer

// Test.java
import java.util.Scanner ;
class Test
{

       public static double sumI (double[] a)
       {
            double result = 0.0;
            int i = 0;
            while (i < a.length)
            {

                result = result + a[i];
                i = i + 1;

            }
            return result;
       }

    // recusive helper function
    public static double sumUtil(double[] a, int n)
    {
       if (n == 0)
       {
           return a[n];
       }

       else
           return a[n] + sumUtil(a,n-1);
    }

    // sum function
    public static double sum (double[] a)
    {

        return sumUtil(a,a.length-1);

    }


   public static void main ( String[] args )
   {
       Test t = new Test();
      
       double[] a = {1,2,3,4.5,6};
      
       System.out.println ( " Sum of array elements is : " +t.sumI(a) ) ;
       System.out.println ( " Sum of array elements is : " +t.sum(a) ) ;
   }
}

/*
output:

Sum of array elements is : 16.5
Sum of array elements is : 16.5


*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote