Recursive Function
Recursive Function
Recursive Function
The Recursive function is a function, that repeatedly calls itself in order to solve a
problem, breaking the problem down into smaller and smaller sub-problems until it
reaches a base case, at which point the solution is built up from the solutions to the
sub-problems. Let’s see how the recursive function looks in C language.
In the below example, the function rec() calls itself so the function rec() is called the
recursive function.
void rec()
{
/* function calls itself */
rec();
}
int main()
{
rec();
}
Let’s see how to find the factorial of the given number using the recursive function.
Output:
In the C program, we have created the recursive function factorial(), in which there is
one base to terminate the recursive class and the base case is n==0 because factorial
of 0 and 1 is 1. If it is not the base case then the function calls itself for the n-1 th term
and multiplies it with n and returns the answer.
Fibonacci series is the series, where the Nth term is the sum of the last term ( N-1 th)
and the second last term (N-2 th).
Let’s see how to find the fibonacci series using the recursive function.
https://www.prepbytes.com/blog/c-programming/what-is-recursive-function-in-c-programming/ 2/4
10/12/23, 11:16 AM What is Recursive Function in C Programming?
int n;
printf("Enter the number: ");
scanf("%d",&n);
int fibo = fibonacci(n);
printf("The %dth Fibonacci number is:
%d\n", n,fibo);
return 0;
}
Output:
In the C program, we have created the recursive function fibonacci(), in which there is
one base to terminate the recursive class and the base case is n<=1 because
Fibonacci of 0 and 1 is 1. If it is not the base case then the function calls itself for the n-
1 th term and adds it with the n-2 th term and returns the answer.
Example 3: GCD of the given two numbers using the recursive function
The greatest common divisor (GCD) of two numbers is the largest positive integer that
divides both of the numbers without leaving a remainder. Let’s see how to find the GCD
of the two numbers using the recursive function.
Output:
https://www.prepbytes.com/blog/c-programming/what-is-recursive-function-in-c-programming/ 3/4
10/12/23, 11:16 AM What is Recursive Function in C Programming?
In the C program, we have created the recursive function gcd(), in which there is one
base to terminate the recursive class and the base case is b==0 we will return a. If it is
not the base case then we will return gcd(b, a%b).
https://www.prepbytes.com/blog/c-programming/what-is-recursive-function-in-c-programming/ 4/4