Fibonacci Series in C

The Fibonacci sequence starts with 0 and 1. Each later term is the sum of the previous two terms: 0, 1, 1, 2, 3, 5, 8....

Print the First 10 Fibonacci Terms Top ↑

#include <stdio.h>

int main(void) {
    unsigned long long first = 0;
    unsigned long long second = 1;

    for (int i = 0; i < 10; i++) {
        printf("%llu", first);

        if (i < 9) {
            printf(", ");
        }

        unsigned long long next = first + second;
        first = second;
        second = next;
    }

    putchar('\n');
    return 0;
}

Output

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Choose the Number of Terms Top ↑

#include <stdio.h>

int main(void) {
    int terms;

    printf("How many terms (1 to 94)? ");
    if (scanf("%d", &terms) != 1 ||
        terms < 1 ||
        terms > 94) {
        printf("Enter a value from 1 to 94.\n");
        return 1;
    }

    unsigned long long first = 0;
    unsigned long long second = 1;

    for (int i = 0; i < terms; i++) {
        printf("%llu", first);

        if (i + 1 < terms) {
            printf(", ");
        }

        unsigned long long next = first + second;
        first = second;
        second = next;
    }

    putchar('\n');
    return 0;
}

The limit of 94 terms keeps this example within the range of a typical 64-bit unsigned long long; larger terms need a wider or arbitrary-precision representation.

Original 1, 2, 3... Variation Top ↑

The old page printed the sums after the initial seeds, producing 1, 2, 3, 5.... If you intentionally want that variation, print next after calculating it:

unsigned long long first = 0;
unsigned long long second = 1;

for (int i = 0; i < 10; i++) {
    unsigned long long next = first + second;
    printf("%llu ", next);
    first = second;
    second = next;
}

Related: for loops and factorial.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer