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 you implement ordinary and tail-recursive summation functions in PHP?ComputerScienceOne · Recursion
- How can a recursive method sum the elements of an array?ComputerScienceOne · Recursion
- How can Fibonacci numbers be computed recursively in Java?ComputerScienceOne · Recursion
- How is recursion implemented in Java?ComputerScienceOne · Recursion
- What happens when a function calls itself?ComputerScienceOne · Recursion
- How can BigInteger be used for large recursive Fibonacci values?ComputerScienceOne · Recursion
- How can a countdown be written without a loop?ComputerScienceOne · Recursion
- How are arrays passed to functions in C?ComputerScienceOne · Using Arrays with Functions