Fibonacci Sequence Generator in C
This snippet calculates the Fibonacci sequence up to the nth term inputted by the user. It initializes the first two terms and then uses a loop to generate the sequence. The results are printed to the console, either separated by spaces or ending with a newline for the last term.#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 - 1)) { printf("%d\n", next); } else printf("%d ", next); } return 0; }
Leave a Comment