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


MORE

Java Program to check Krishnamurthy Number

In this tutorial, we will learn about Krishnamurthy numbers and write a Krishnamurthy Number program in Java. We will write two programs for Krishnamurthy number …
Read More

Java Program for ISBN Number

In this tutorial, we will learn about the ISBN (International Standard Book Number) and write a program to check for the ISBN Number in Java …
Read More

C++ Memory Management

Memory management refers to the process of managing the computer memory while assigning the space to the program’s variable to improve the overall performance. Requirement …
Read More

C++ Pointer to Pointer

As we know by now that a pointer stores the address of the pointed variable. But it is not the only use, pointer also stores …
Read More

C++ Passing Pointers to Functions

A function is a user-defined block of codes that executes some specific task assigned to it invoked by its name. If there is an argument …
Read More

C++ Null Pointer

We use a null pointer when we do not have the exact address to assign to a pointer. It is considered a good practice and …
Read More