Hey guys, what is up. In this particular post, we will be talking about the what is recursion? Also, we will see some examples of recursive function.
What is Recursion?
Recursion is the procedure of repeating items in a way similar to itself at different times. In programming languages, if a program allows you for calling a function itself continuously within the same function, then it is known as a recursive function.
The C language uses recursion, i.e., a function for calling itself. But at the time of using a recursive function, everyone must be attentive to define an exit condition for the function. Otherwise, it will call itself infinite times and will become an infinite loop.
Recursive functions are extremely helpful for solving numerous arithmetic difficulties, like computing a factorial, creating Fibonacci series.
THE THREE LAWS OF RECURSION –
Every recursive algorithm should follow three main laws:
- A recursive algorithm should call itself, recursively.
- Recursive problem should have a base case.
- A recursive algorithm should change its value continuously and move toward the exit statement or base case.
A base case is a state that permits the algorithm to stop recursing. A base case is typically a difficulty that is too small to be solved directly. In the factorial problem, the base case is n=1.
We must organize a way for a change of statements so that the program moves toward the exit statement. A change of state means that specific data that the algorithm is using is modified. Normally, the data that illustrates our problem gets smaller in some way. In the factorial problem, n decreases.
long fact(int x)
if (x == 0)
return(x * fact(x-1));
printf(“Enter a number: “);
factorial = fact(num);
printf(“Factorial of is equals to %d\n”, factorial);
FIBONACCI SERIES –
void fibonacci(int x)
static int x1=0,x2=1,x3;
x3 = x1 + x2;
x1 = x2;
x2 = x3;
printf(“Enter the number of elements: “);
printf(“Fibonacci Series: “);
printf(“%d %d “,0,1);
fibonacci(x-2);//n-2 because 2 numbers are already printed
In the upcoming post, you will be getting information related to Samsung A51 Simple smartphone. If you haven’t seen our previous post on what is function in c programming and actual and formal parameters in c then go and see our previous posts.