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....
#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
#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.
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.