In this example, you will learn to display the Fibonacci sequence of first n numbers (entered by the user).
To understand this
example, you should have the knowledge of the following C programming topics:
C
Programming Operators
C while and
do...while Loop
C for Loop
C break and
continue
The
Fibonacci sequence is a sequence where the next term is the sum of the previous
two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
Visit this page to learn about the Fibonacci sequence.
Fibonacci Series up to n terms
#include <stdio.h>
int main() {
int i, n;
// initialize first and second terms
int t1 = 0, t2 = 1;
// initialize the next term (3rd term)
int nextTerm = t1 + t2;
// get no. of terms from user
printf("Enter the number of terms: ");
scanf("%d", &n);
// print the first two terms t1 and t2
printf("Fibonacci Series: %d, %d, ", t1, t2);
// print 3rd to nth terms
for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Let us suppose n = 10
. First, we have printed the first
two terms of the Fibonacci sequence before using a for
loop to print the next n terms.
Let us see how the for
loop works:
Fibonacci
Sequence Up to a Certain Number
i |
t1 |
t2 |
nextTerm |
3 |
0 |
1 |
1 |
4 |
1 |
1 |
2 |
5 |
1 |
2 |
3 |
6 |
2 |
3 |
5 |
7 |
3 |
5 |
8 |
8 |
5 |
8 |
13 |
9 |
8 |
13 |
21 |
10 |
13 |
21 |
34 |
#include
int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("Enter a positive number: ");
scanf("%d", &n);
// displays the first two terms which is always 0 and 1
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while (nextTerm <= n) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output
Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
In this
program, we have used a while loop to print all the Fibonacci
numbers up to n.
If n is not part of the Fibonacci sequence, we print
the sequence up to the number that is closest to (and lesser than) n.
Suppose n = 100.
First, we print the first two terms t1 =
0 and t2 = 1.
Then
the while loop prints the rest of
the sequence using the nextTerm variable:
t1 |
t2 |
nextTerm |
nextTerm <= n |
0 |
1 |
1 |
true. Print nextTerm. |
1 |
1 |
2 |
true. Print nextTerm. |
1 |
2 |
3 |
true. Print nextTerm. |
... |
... |
... |
... |
34 |
55 |
89 |
true. Print nextTerm. |
55 |
89 |
144 |
false. Terminate Loop. |