Ema - 6 months ago 35

C Question

I have this recursive function to add the cubes of n even numbers and I want't to turn it to a tail recursion.

`int sum_even_cubes_rec(int n) {`

if (n < 2)

return 0;

if ((n % 2) == 0) {

return (n*n*n + sum_even_cubes_rec(n - 1));

} else {

return (0 + sum_even_cubes_rec(n - 1));

}

}

This is what I wrote but it is wrong and I don't know how to fix it.

Can you please help me.

`int sum_even_cubes_rec2(int n, int acc) {`

if ((n % 2) == 0) {

return sum_even_cubes_rec2 (n-1, acc + n*n*n);

} return acc;

}

int sum_even_cubes_helperFunktion(int n) {

return sum_even_cubes_rec2(n, 0);

}

Answer

Your approach is correct. You have already added `acc`

argument, so that's what you need to return for the base case.

The rest of your code is almost right - you need to adjust what you add to `acc`

for the next invocation:

```
int sum_even_cubes_rec2(int n, int acc) {
if (n < 2) {
return acc;
}
int nextAcc = (n % 2) == 0 ? acc + n*n*n : acc;
return sum_even_cubes_rec2 (n-1, nextAcc);
}
```