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

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …

Java Program to Find pair of Integers in Array whose sum is given Number

In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java …

Program to Print Diamond Alphabet Patterns in C

In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a …

Half Diamond Pattern in C using Alphabets

In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a …

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …