I have written the code to sum up elements of an array with
Recursion
static int sum(int[] array)
{
if (array.Length == 1)
return array[0];
else
{
int[] newArr = new int[array.Length - 1];
for (int i = 1; i < array.Length; i++)
{
newArr[i - 1] = array[i];
}
return array[0] + sum(newArr);
}
}
and with
Tail Recursion
static int sumTR(int[] array, int sum)
{
//base case
if (array.Length == 1)
return array[0] + sum;
else
{
//tail recursive case
int[] newArr = new int[array.Length - 1];
for (int i = 1; i < array.Length; i++)
newArr[i - 1] = array[i];
return sumTR(newArr, array[0] + sum);
}
}
As I understood, in the tail recursion the base method shouldn't be waiting for the recursive method to finish executing and shouldn't be dependent on its output. Is this implementation the right way to achieve that?