Program to find Fibonacci Series up to n number of terms

Program to find Fibonacci Series up to n number of terms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
using namespace std;

int main()
{
    int n, t1 = 0, t2 = 1, nextTerm = 0;

    cout << "Enter the number of terms: ";
    cin >> n;

    cout << "Fibonacci Series: ";

    for (int i = 1; i <= n; ++i)
    {
        // Prints the first two terms.
        if(i == 1)
        {
            cout << " " << t1;
            continue;
        }
        if(i == 2)
        {
            cout << t2 << " ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        
        cout << nextTerm << " ";
    }
    return 0;
}
Last edited on
and the question is..........
after you get past roundoff error in the first few terms its just a constant * previous value.
hard code the first few and let it roll. Or, hard code then all into a table: fib is like factorial, computing them is kind of silly, there are not many that fit into even a 64 bit int. You should always use a lookup table for things with exponential, factorial, etc growth rates rather than fool with computing them over and over.
Last edited on
Topic archived. No new replies allowed.