How to implement the recursive method for Fibonacci sequence in C language?

In C language, the Fibonacci sequence can be implemented using recursion. The concept of recursion involves breaking down a problem into smaller sub-problems, reaching a base case, and then gradually combining the solutions of the sub-problems to get the solution to the entire problem.

Here is an example code implementing the recursive method for Fibonacci sequence.

#include <stdio.h>

int fibonacci(int n) {
    // 基本情况:当 n 为 0 或 1 时,直接返回 n
    if (n == 0)
        return 0;
    if (n == 1)
        return 1;
    // 递归调用:将问题分解为子问题
    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    int n;
    printf("请输入斐波那契数列的项数:");
    scanf("%d", &n);
    printf("斐波那契数列的第 %d 项为:%d\n", n, fibonacci(n));
    
    return 0;
}

The above code utilizes the Fibonacci function with recursive calls. It returns n directly when n is 0 or 1. Otherwise, it breaks down the problem by calculating the Fibonacci sequence for n-1 and n-2, then adds the results.

In the main function, the user can input the number of terms n in the Fibonacci sequence, then call the fibonacci function to calculate the nth term, and print the result.

bannerAds