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.
void function_name() {
function_name(); /* function calls itself */}
int main() {
function_name();
}
#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;
}
5
Factorial of 5 is 120
Here, the factorial() function is a recursive function that calls itself till the number becomes 1.
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;
}
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
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…