Concept

How can recursion be made tail-recursive in C?

ComputerScienceOne / Recursion

"This example was not tail-recursive as the recursive call was not the final operation (the sum was the final operation). To make this function tail recursive, we can carry the summation through to each function call ensuring that the summation is done prior to the recursive function call.\n\nint recSumTail(const int *arr, int size, int i, int sum) {\n\nif(i == size) {\n\nreturn sum;\n\n} else {\n\nreturn recSumTail(arr, size, i+1, sum + arr[i]);\n\n}\n\n}\n\nAs a final example, consider the following C implementation of the naive recursive Fibonacci sequence. An additional condition has been included to check for “invalid” negative values of n for which zero is returned.\n\nint fibonacci(int n) {\n\nif(n < 0) {\n\nreturn 0;\n\n} else if(n <= 1) {\n\nreturn 1;\n\n} else {\n\nreturn fibonacci(n-1) + fibonacci(n-2);\n\n}\n\n}"

Related Ideas

How can recursion be made tail-recursive in C? | ComputerScienceOne | Bifalgorithm | Bifalgorithm