Discussion: Cursing Recursion
Execute the code to understand the output and gain insights into recursive computation.
We'll cover the following...
Run the code
Now, it's time to execute the code and observe the output.
#include <stdio.h> long result(long v) { if( v>1 ) return(v*result(v-1)); return(v); } int main() { long a,r; printf("Enter a positive integer: "); scanf("%ld", &a); r = result(a); printf("The result is %ld\n", r); return(0); }
The code outputs the factorial for the value input. For example, four:
Enter a positive integer: 4The result is 24
Explanation
Recursion is a programming concept that works like a loop. But instead of a chunk of code repeating, a function calls itself over and over—like a drunken ex who just can’t let go, but with all the logic you expect from computer programming.
As with a loop, a terminating condition exists for a recursive function. When it’s encountered, the recursion unwinds: the function returns to itself again and again until it eventually returns to the caller.
Indeed, recursion truly is insane, but it offers many practical solutions for adept coders who understand the insanity and can manipulate it in a beneficial manner.
Understanding the output
The sample code uses ...