Concept

How can recursive functions be written in C?

ComputerScienceOne / Recursion

"C supports recursion with no special syntax necessary. However, as a structured, procedural language, recursion is generally expensive and iterative or other non-recursive solutions are generally preferred. We present a few examples to demonstrate how to write recursive functions in C. The first example of a recursive function we gave was the toy count down example. In C it could be implemented as follows.\n\nvoid countDown(int n) {\n\nif(n==0) {\n\nprintf(\"Happy New Year!\n\n\");\n\n} else {\n\nprintf(\"%d\n\n\", n);\n\ncountDown(n-1);\n\n}\n\n}\n\nAs another example that actually does something useful, consider the following recursive summation function that takes an array, its size 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 function returns, it adds its result to the i-th element in the array. To invoke this function we would call it with an initial value of 0 for the index variable: recSum(arr, n, 0).\n\nint recSum(const int *arr, int size, int i) {\n\nif(i == size) {\n\nreturn 0;\n\n} else {\n\nreturn recSum(arr, size, i+1) + arr[i];\n\n}\n\n}"

Related Ideas

How can recursive functions be written in C? | ComputerScienceOne | Bifalgorithm | Bifalgorithm