Bifalgorithm post · Computer science one · Recursion

How can a recursive method sum the elements of an array?

How can a recursive method sum the elements of an array? (Computer science one · Recursion) — "As another example that actually does something useful, consider…

Ideas in this flowchart

  • Recursion and tail recursion for array summation
  • The recursive method processes an array using an index variable.
  • When the index reaches the array size, the method returns zero and stops.
  • Otherwise, recSum() calls itself with the index increased by one.
  • After the recursive call returns, its result is added to arr[i].
  • The method is initially invoked as recSum(arr, 0).
  • The original method is not tail-recursive because addition occurs after the recursive call.
  • The tail-recursive version carries the summation through each method call.
  • recSumTail() receives an additional sum parameter.
  • When the index reaches the array size, the tail-recursive method returns sum.
  • Otherwise, it calls recSumTail() with i + 1 and sum + arr[i].
Feed/

How can a recursive method sum the elements of an array?

No cover

Channel

Computer science one

1 page

"As another example that actually does something useful, consider the following recursive summation method that takes an array and an index variable. The recursion works as follows: if the index variable has reached the size of the array, it stops and returns zero (the base case). Otherwise, it makes a recursive call to recSum(), incrementing the index variable by 1. When the method returns, it adds its result to the i-th element in the array. To invoke this method we would call it with an initial value of 0 for the index variable: recSum(arr, 0).\n\n1 public static int recSum(int arr[], int i) {\n\n2 if(i == arr.length) {\n\n3 return 0;\n\n4 } else {\n\n5 return recSum(arr, i+1) + arr[i];\n\n6 }\n\n7 }\n\nThis example was not tail-recursive as the recursive call was not the final operation (the sum was the final operation). To make this method tail recursive, we can carry the summation through to each method call ensuring that the summation is done prior to the recursive method call.\n\n1 public static int recSumTail(int arr[], int i, int sum) {\n\n2 if(i == arr.length) {\n\n3 return sum;\n\n4 } else {\n\n5 return recSumTail(arr, i+1, sum + arr[i]);\n\n6 }\n\n7 }"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.