Easy Tutorial
❮ C Examples Factors Number C Examples Add Matrix ❯

C Language Example - Fibonacci Sequence

C Language Examples

The Fibonacci sequence is a series of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368...

Starting from the third term, each term is the sum of the two preceding 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;
}

Execution Result:

Output how many terms: 10
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Example - Output the Fibonacci Sequence Up to 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;
}

Execution Result:

Enter a positive number: 100
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

C Language Examples

❮ C Examples Factors Number C Examples Add Matrix ❯