Bifalgorithm post · Computer science one · Recursion

How can recursive functions be written in C?

How can recursive functions be written in C? (Computer science one · Recursion) — "C supports recursion with no special syntax necessary. However, as a structu…

Ideas in this flowchart

  • Recursion in C
  • C supports recursion without special syntax.
  • Recursion is generally expensive in C, so iterative or other non-recursive solutions are usually preferred.
  • Examples of recursive functions
  • The countDown function demonstrates a simple recursive countdown.
  • Does n equal zero?
  • If n equals zero, the function prints “Happy New Year!”
  • Otherwise, it prints n and calls countDown with n - 1.
  • The recSum function recursively sums the elements of an array.
  • recSum receives an array, its size, and an index variable.
  • Has the index reached the array size?
  • If the index equals the size, the function returns zero as the base case.
  • Otherwise, it recursively increments the index and adds the returned result to arr[i].
  • The function is invoked as recSum(arr, n, 0), starting the index at zero.
Feed/

How can recursive functions be written in C?

No cover

Channel

Computer science one

1 page

"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}"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.