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.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…