Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

1.

#include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. int n, t1 = 0, t2 = 1, nextTerm = 0;
7.
8. cout << "Enter the number of terms: ";
9. cin >> n;
10.
11. cout << "Fibonacci Series: ";
12.
13. for (int i = 1; i <= n; ++i)
14. {
15. // Prints the first two terms.
16. if(i == 1)
17. {
18. cout << " " << t1;
19. continue;
20. }
21. if(i == 2)
22. {
23. cout << t2 << " ";
24. continue;
25. }
26. nextTerm = t1 + t2;
27. t1 = t2;
28. t2 = nextTerm;
29.
30. cout << nextTerm << " ";
31. }
32. return 0;
33. }
Output
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Example 2: Program to Generate Fibonacci


Sequence Up to a Certain Number
1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. int t1 = 0, t2 = 1, nextTerm = 0, n;
7.
8. cout << "Enter a positive number: ";
9. cin >> n;
10.
11. // displays the first two terms which is always 0 and 1
12. cout << "Fibonacci Series: " << t1 << ", " << t2 << ", ";
13.
14. nextTerm = t1 + t2;
15.
16. while(nextTerm <= n)
17. {
18. cout << nextTerm << ", ";
19. t1 = t2;
20. t2 = nextTerm;
21. nextTerm = t1 + t2;
22. }
23. return 0;
24. }

You might also like