C – Recursion2 min read

Recursion refers to the process when a function calls itself inside that function directly or indirectly or in a cycle. And such functions are called recursive functions. However, the crucial part is the termination condition that is given to the recursive function because it might go into an infinite loop.

If the termination is not processed properly then that will lead to stack overflow (recursion invokes stack memory) which will lead to a system crash. It could be a little hard to understand the recursive code but the code becomes shorter than the iterative code.

Recursion

Recursion is very useful in performing mathematical calculations such as during the calculation of factorial of a number, Fibonacci series problem, etc. Although any problem that can be performed by recursion can also be done iteratively.

But sometimes it is best-suited to use recursion such as the tower of Hanoi, Factorial and Fibonacci calculation, etc.


What is base condition?

In recursion, the larger problem is solved in terms of smaller problems, and the larger value is solved by converting into a smaller value still the base condition is reached by the function. It is the condition when the computing is complete and needs to get out of the function.


What do you mean by direct and indirect recursion?

When the function call itself (same function), it is called a direct call. When some function is called inside another function then it is said to be an indirect call. Relate to the example given below:


Factorial Program in C using Recursion

factorial of n (n!) = n * (n-1) * (n-2) * (n-3)….1
factorial of 5 (n!) = 5 * 4 * 3 * 2 * 1
NOTE: Factorial of 0 (0!) = 1

Output:

Enter the Number to Find the Factorial of: 5
Factorial of 5 is: 120


MORE

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More

Keith Number Program in C++

In this tutorial, we will write a Keith number in C++. It is one of the most asked questions in an interview. Before that, you …
Read More

Singly linked list Program C++

In this tutorial, we will write a C++ program to implement singly linked list. In this program, we will create a separate function for each …
Read More

Fascinating Number Program in C

In this tutorial, we will write a C program to check whether the given number is a Fascinating number or not. You may go through …
Read More

Peterson Number in C

In this tutorial, we will learn about the Peterson number and check if the number is Peterson or not in C. What is Peterson Number? …
Read More

Peterson Number in C++

In this tutorial, we will learn about the Peterson number and write a C++ program to check if the given number is a Peterson number …
Read More