Recursion in C Programming

Filter Course


Recursion in C Programming

Published by: Zaya

Published date: 17 Jun 2021

Recursion in C Programming Photo

Recursion in C Programming

Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process".
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion in C programming, programmers need to be careful to define an exit condition from the function, otherwise, it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating the Fibonacci series, etc.

Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −

#include

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;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34