C Programming

Recursion in C

Recursion is a process in which function call itself and the function that calls itself directly or indirectly called a recursive function. A recursive function calls itself so there can be several numbers of the recursive call, so the recursive function should have the termination condition to break the recursion. If there is a not termination condition in a recursive function, a stack overflow will occur and your program will crash.

Recursive functions are useful to solve many mathematical problems, like generating the Fibonacci series, calculating the factorial of a number, and convenient for recursively defined data structures like trees.

For example:

#include <stdio.h>
int factorial(int number);
int main() {    
  int x = 6;
  printf("The factorial of %d is %d\n", x, factorial(x)); 
  return 0;}
int factorial(int number) {
 if (number == 1)    return (1); /* exiting condition */
  else
    return (number * factorial(number - 1));
}
Output

The factorial of 6 is 720

Here, we discuss program details:

  • We declare our recursive factorial function which takes an integer parameter and returns the factorial of this parameter. This function will call itself and decrease the number until the exiting, or the base condition is reached. When the condition is true, the previously generated values will be multiplied by each other, and the final factorial value is returned.
  • We declare and initialize an integer variable with value”6″ and then print its factorial value by calling our factorial function.

Consider the following chart to more understand the recursive mechanism which consists of calling the function its self until the base case or stopping condition is reached, and after that, we collect the previous values:

Premium E-Books & Study Materials.

Access university-specific notes and programming guides. Download instantly to start studying.

Share Article :

TopperWorld
Prime E-Books

Master programming and core CS concepts with expert-curated study guides.

Recent Tutorials :

What Jobs Will AI Replace: Which Careers Will Grow in the Next 5 Years?
Java Most Asked Interview Question and Answer
Top 10 AI companies in India
How Generative AI is Transforming Programming
Top GITHUB Interview Questions and Answers