C Language Examples - Fibonacci Sequence

C 语言实例C Language Examples

The Fibonacci sequence refers to the sequence 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368........

This sequence starts from the 3rd term, and each term is equal to the sum of the previous two terms.

Example - Output a specified number of Fibonacci sequence terms

#include <stdio.h> int main() { int i, n, t1 = 0, t2 = 1, nextTerm; printf("Output how many terms:"); scanf("%d", &n); printf("Fibonacci sequence:"); for (i = 1; i <= n; ++i) { printf("%d, ", t1); nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; } return 0; }

Run result:

输出几项: 10
斐波那契数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Example - Output the Fibonacci sequence before a specified number

#include <stdio.h> int main() { int t1 = 0, t2 = 1, nextTerm = 0, n; printf("Enter a positive number:"); scanf("%d", &n); // Display the first two terms printf("Fibonacci sequence: %d, %d,", t1, t2); nextTerm = t1 + t2; while(nextTerm <= n) { printf("%d, ",nextTerm); t1 = t2; t2 = nextTerm; nextTerm = t1 + t2; } return 0; }

Run result:

输入一个正数: 100
斐波那契数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

C Language Examples

other extensions