In the C programming language, a function may call itself. A function is called recursive if a statement within the body of the function calls the same function. Sometimes called ‘circular definition’- therefore, recursion is the process of defining something in terms of itself.
Recursion cannot be applied to all the problems, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal issues.
Syntax:
void function_name() {
function_name(); /* function calls itself */
}
int main() {
function_name();
}
Key points:
- A recursive function executes the tasks by dividing them into subtasks.
- The recursion stops and the final result is returned from the function when a termination condition defined in the function is met at some point by some specific subtask.
- The base case is the case at which the function doesn’t recur.
- The recursive case is the instance where the function keeps calling itself to perform a subtask.
Example: Factorial of a number
#include <stdio.h>
int factorial(int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i ;
scanf("%d",&i);
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
Output:
5
Factorial of 5 is 120
Here, the factorial() function is a recursive function that calls itself till the number becomes 1.
Example: Fibonacci series
The Fibonacci series is a sequence where the next term is the sum of the last two terms. The first two terms of the Fibonacci series are 0 followed by 1.
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d\t\n", fibonacci(i));
}
return 0;
}
Output:
0
1
1
2
3
5
8
13
21
34
Note: also read about the Passing arguments between functions in C & Call by Value & Call by Reference
Follow Me
If you like my post, please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment