Loading your workspace…
Loading your workspace…
Read n and print the first n terms of the Fibonacci sequence, where each term is the sum of the two before it.
#include <stdio.h>
int main(void) {
int n, i, a = 0, b = 1, next;
printf("Enter the number of terms (at least 1):\n");
if (scanf("%d", &n) != 1 || n < 1) {
printf("Error: enter a positive number of terms\n");
return 1;
}
for (i = 1; i <= n; i++) {
printf("%d", a);
if (i < n) {
printf(" ");
}
next = a + b;
a = b;
b = next;
}
printf("\n");
return 0;
}
Input
7Output
Enter the number of terms (at least 1):
0 1 1 2 3 5 8Input
1Output
Enter the number of terms (at least 1):
0Two variables carry the last two terms. Each step prints the current term and then shifts the pair forward, so no array is needed.
The space is printed only between terms, so the output has no trailing space and reads exactly as the sequence.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
7
Expected output
Enter the number of terms (at least 1): 0 1 1 2 3 5 8
1
Expected output
Enter the number of terms (at least 1): 0
F(n) = F(n - 1) + F(n - 2), with F(0) = 0 and F(1) = 1.
The new sum uses a and b before they are overwritten, so it must be stored first.
0.
Only the last two terms are needed, so two variables are enough.
Around the 47th term, so very large n needs a wider type.
Back to all RCU 21BCA1C1P lab programs.