...

/

Discussion: Cursing Recursion

Discussion: Cursing Recursion

Execute the code to understand the output and gain insights into recursive computation.

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);
}
C code for the given puzzle

The code outputs the factorial for the value input. For example, four:

Enter a positive integer: 4
The result is 24
Code output

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 ...