Fibonnaci Numbers in C++

Hi,
how can display fibonacci numbers example is "2 2 4 6 8". user will enter starting number is "2" then number of sequence is "5"
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
  #include <iostream>
using namespace std;
int main ()
{
    int n;
    int s;
    int b;

do
{
    cout << "Enter Starting Number: ";
    cin >> n;
    
        if (n<1 || n>9)
        cout << "Invalid Input" <<endl;
        }
    while (n<1 || n>9);
    do {
        cout << "Enter number of sequence: ";
        cin >> s;
        if (s<5 || s>20)
        cout << "Invalid Input" <<endl;
            }while (s<5 || s>20);
            cout <<n <<" " <<n <<" ";
            \\don't know what to use next if for loop or a simple addition
            

system("pause");
return 0;
}
 
Fibonacci numbers? Yours does not look like http://en.wikipedia.org/wiki/Fibonacci_number

What does the "starting number" mean?
fn = fn-1 + fn-2

Therefore f0 is congruent with f1

Which means your results should be "2 2 4 6 10"

A very inefficient way would be recursion like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int fibonacci(int start, int n)
{
    if(n < 2) //0 or 1
        return start;
    else
        return fibonacci(start, n - 1) + fibonacci(start, n - 2);
}

int main()
{
    std::cout << "Please enter the starting number: ";
    std::size_t start = 0u;
    std::cin >> start;
    
    std::cout << "Please enter the number of terms: ";
    std::size_t terms = 0u;
    std::cin >> terms;
    
    for(std::size_t i = 0u; i < terms; ++i)
        std::cout << fibonacci(start, i) << ' ';
}
Please enter the starting number: 2
Please enter the number of terms: 5
2 2 4 6 10  


It would be more efficient to use an array to access the previous values since they are being accessed multiple times or to fix the function but I am very tired right now.

By the way after thinking you could simply use a loop

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
#include <iostream>

int main()
{
    std::cout << "Please enter seed: ";
    std::size_t seed = 0u;
    std::cin >> seed;
    
    std::cout << "Please enter terms: ";
    std::size_t terms = 0u;
    std::cin >> terms;
    
    //n1 and n2 will be f[0] and f[1] to start
    std::size_t n1 = seed; //n-1
    std::size_t n2 = seed; //n-2
    
    std::cout << n1 << ' ' << n2 << ' ';
    for(std::size_t term = 2u; term < terms; ++term) //already have the first 2
    {
        std::size_t temp = n1 + n2;
        n1 = n2;
        n2 = temp;
        std::cout << n2 << ' ';
    }
    
    return 0;
}


Last edited on
Topic archived. No new replies allowed.