Fibonacci Sequence Generator in C

This C program generates the Fibonacci sequence up to a user-defined number of terms. It prompts the user to enter the number of terms and then calculates the sequence, printing each term in order. The implementation utilizes a simple loop structure to achieve this.
 avatar
unknown
c_cpp
17 days ago
393 B
3
Indexable
#include <stdio.h>
int main()
{
    int n;
    int t1 = 0, t2 = 1;
    scanf("%d", &n);
    printf("%d %d ", t1, t2);
    for (int i = 0; i < (n - 2); i++)
    {
        int next = t1 + t2;
        t1 = t2;
        t2 = next;
        if (i == (n - 3))
        {
            printf("%d\n", next);
        }
        else
            printf("%d ", next);
    }
    return 0;
}
Leave a Comment