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:

  1. #include <stdio.h>: Includes the standard input-output header file in C.

  2. int fibonacci(int n);: Function prototype for the fibonacci function that calculates the nth term in the Fibonacci series.

  3. int main() { ... }: The main function where the program execution starts.

  4. int n, i;: Declares integer variables n (for the number of terms) and i (for iteration).

  5. printf("Enter the number of terms: ");: Displays a message to prompt the user to enter the number of terms in the Fibonacci series.

  6. scanf("%d", &n);: Reads the user input for the number of terms and stores it in the variable n.

  7. printf("Fibonacci Series: ");: Prints a message to indicate the display of the Fibonacci series.

  8. for (i = 0; i < n; i++) { ... }: A loop that iterates n times to print the Fibonacci series up to the nth term.

  9. printf("%d ", fibonacci(i));: Calls the fibonacci function for each value of i and prints the corresponding term in the series.

  10. int fibonacci(int n) { ... }: Definition of the fibonacci function that calculates the nth term recursively.

  11. if (n <= 1) { return n; }: Base case check; if n is 0 or 1, it returns n.

  12. 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.