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
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:
| 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 |
Fibonacci Sequence Up to a Certain Number
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. |