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

The following procedure uses recursion to accumulate a sum: int sum (int n, int

ID: 3837057 • Letter: T

Question

The following procedure uses recursion to accumulate a sum: int sum (int n, int acc) { if (n > 0) return sum (n - 1, acc + n); else return acc; } (i)Consider the initial procedure call sum (3, 0). How many recursive calls does this initial call generate? GFive the two arguments of each recursive cell as well as the return value of each. What is the final result returned? (ii) To avoid the overhead of recursion, you decided to re-write the sum(int n, int acc) function so it it is implemented iteratively, i.e., using a while loop. Complete the following iterative version- you can only use the variables n and acc. Int sum(int n, int acc) { while (_______________) { _______; _______; } return acc; }

Explanation / Answer

Answer to Question a
1st call to sum value of n is 3 and acc is 0
   Calls the method recursively n is now 2 and acc is 3
   Calls the method recursively n is now 1 and acc is 5
   Calls the method recursively n is now 0 and acc is 6
   recursion stops and the value of n is 0 and acc is 6
  
Total recursion call is 3


Answer to Question b

//We will be using the while loop and check if n>0. If yes then execute the loop and add the value of n to it
int sum(int n, int acc){
       while(n>0){
           acc=acc+n;//adding n to acc
           n--;// subtracting n by 1
       }
       return acc;
}

//Note : Feel free to ask question if any. Happy to help. God bless you!!