c fibonacci series recursion
#include <stdio.h>
int fibonacci(int n);
int main() {
int n, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
Explanation:
#include <stdio.h>
: Includes the standard input-output header file in C.int fibonacci(int n);
: Function prototype for thefibonacci
function that calculates the nth term in the Fibonacci series.int main() { ... }
: The main function where the program execution starts.int n, i;
: Declares integer variablesn
(for the number of terms) andi
(for iteration).printf("Enter the number of terms: ");
: Displays a message to prompt the user to enter the number of terms in the Fibonacci series.scanf("%d", &n);
: Reads the user input for the number of terms and stores it in the variablen
.printf("Fibonacci Series: ");
: Prints a message to indicate the display of the Fibonacci series.for (i = 0; i < n; i++) { ... }
: A loop that iteratesn
times to print the Fibonacci series up to then
th term.printf("%d ", fibonacci(i));
: Calls thefibonacci
function for each value ofi
and prints the corresponding term in the series.int fibonacci(int n) { ... }
: Definition of thefibonacci
function that calculates the nth term recursively.if (n <= 1) { return n; }
: Base case check; ifn
is 0 or 1, it returnsn
.return fibonacci(n - 1) + fibonacci(n - 2);
: Recursive call to calculate the Fibonacci series for values greater than 1 by summing the (n-1)th and (n-2)th terms.