How to write code to implement the Fibonacci sequence in C language?

Here is an example of C code implementing the Fibonacci sequence:

#include <stdio.h>

int fibonacci(int n) {
    if (n <= 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

int main() {
    int n;
    printf("请输入一个正整数:");
    scanf("%d", &n);
    
    printf("斐波那契数列的前 %d 项为:", n);
    for (int i = 0; i < n; i++) {
        printf("%d ", fibonacci(i));
    }
    
    return 0;
}

In this code, the function fibonacci() is implemented recursively to calculate the nth term of the Fibonacci sequence. The main() function takes a positive integer input from the user and uses a loop to call the fibonacci() function to print the first n terms of the Fibonacci sequence.

bannerAds