Write a C program to find the Fibonacci sequence of n terms using recursion.
Understand the Problem
The question is asking to write a C program that calculates the Fibonacci sequence for a given number of terms using recursion.
Answer
The C program recursively calculates the Fibonacci sequence.
Answer for screen readers
The C program to calculate the Fibonacci sequence recursively is:
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int terms, i;
printf("Enter the number of terms: ");
scanf("%d", &terms);
printf("Fibonacci Series: ");
for (i = 0; i < terms; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
Steps to Solve
-
Define the Fibonacci Function Create a recursive function that calculates the Fibonacci number for a given term. The Fibonacci sequence is defined as follows:
- $F(0) = 0$
- $F(1) = 1$
- For $n \geq 2$, $F(n) = F(n-1) + F(n-2)$.
In C, this can be defined as:
int fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); }
-
Implement the Main Function Create a
main
function to read the number of terms from the user and print the Fibonacci sequence using a loop that calls the Fibonacci function.Here's an example implementation:
#include <stdio.h> int fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } int main() { int terms, i; printf("Enter the number of terms: "); scanf("%d", &terms); printf("Fibonacci Series: "); for (i = 0; i < terms; i++) { printf("%d ", fibonacci(i)); } return 0; }
-
Compile and Run the Program Use a C compiler (like GCC) to compile your program and execute it. Make sure to input a non-negative integer when prompted for the number of terms.
The C program to calculate the Fibonacci sequence recursively is:
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int terms, i;
printf("Enter the number of terms: ");
scanf("%d", &terms);
printf("Fibonacci Series: ");
for (i = 0; i < terms; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
More Information
The Fibonacci sequence is a series where each number is the sum of the two preceding ones, usually starting with 0 and 1. This program utilizes recursion to calculate each Fibonacci term. Note that while recursion is elegant, it may not be the most efficient method for larger values of n
due to repeated calculations.
Tips
- Entering Negative Numbers: Always ensure the input is a non-negative integer.
-
Forgetting to Include Libraries: Make sure to include
#include <stdio.h>
for input/output functions. - Misunderstanding Recursion: Ensure the base case and recursive calls are correctly defined to avoid infinite recursion.
AI-generated content may contain errors. Please verify critical information