Here’s a simple C program to generate the Fibonacci series using recursion:
Simple Fibonacci Series program
#include <stdio.h>
// Recursive function to return the nth Fibonacci number
int fibonacci(int n) {
if (n <= 1)
return n;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
int main() {
int n, i;
// Input the number of terms
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
// Generate and print the Fibonacci series
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
Detailed Explanation of the Recursive Fibonacci Program
Let’s break down the program step by step to understand how the Fibonacci series is generated using recursion:
- Recursive Function: The
fibonacci
function takes an integern
and returns the nth Fibonacci number. The base cases are whenn
is 0 or 1, returningn
directly. For other values, the function calls itself withn-1
andn-2
and returns their sum.
int fibonacci(int n) {
if (n <= 1)
return n;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
- Input the Number of Terms: The
main
function starts by asking the user to enter the number of terms they want in the Fibonacci series.
printf("Enter the number of terms: ");
scanf("%d", &n);
- Generate and Print the Fibonacci Series: A
for
loop is used to generate the Fibonacci series. The loop calls thefibonacci
function for each term and prints the result.
printf("Fibonacci Series: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
Testing the Recursive Fibonacci Program in C
When you run the program, it will prompt you to enter the number of terms. For example:
Enter the number of terms: 10
The output will be the first 10 terms of the Fibonacci series:
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Conclusion
Generating the Fibonacci series using recursion is an excellent way for beginners to understand how recursive functions work in C programming. While the recursive method is simple and elegant, it can be inefficient for large values of n
due to repeated calculations. For such cases, iterative methods or memoization can be more efficient.
Feel free to leave your questions or comments below if you need further assistance or clarification. Happy coding with Fibonacci series in C programming!