Skip to content
Circuit

Fibonacci Sequence in C

Loops

Generate Fibonacci numbers by retaining only the previous two values.

Complete program

#include <stdio.h>

int main(void) {
    int count;
    unsigned long long a = 0, b = 1;
    printf("Terms (1 to 50): ");
    if (scanf("%d", &count) != 1 || count < 1 || count > 50) return 1;
    for (int i = 0; i < count; ++i) {
        printf("%llu%s", a, i + 1 == count ? "\n" : " ");
        unsigned long long next = a + b;
        a = b;
        b = next;
    }
    return 0;
}

Try in Circuit →

Opens a new program without replacing your saved code. Press Run when you are ready.

How it works

Each next value is the sum of the two previous values. A temporary stores the sum before either old value is replaced. This uses constant extra space and one iteration per printed term.

The count limit avoids overflow and excessive output. Swapping the assignment order without preserving the old values changes the recurrence. Trace a, b, and next on paper for the first three iterations.

Sample input

8

Enter these values when prompted. The transcript below includes typed responses.

Expected output

Terms (1 to 50): 8
0 1 1 2 3 5 8 13

Concepts to practice

  • State updates
  • Temporary variables
  • Sequences

Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.