Fibonacci Array

So far, Arrays seem to be the most complex structure that I've ran to as a beginner to C++.

The current task I'm stuck at at the moment is to produce the Fibonacci sequence, which contains the numbers 0, 1, 1, 2, 3, 5, 8, 13, ..., where each number is the sum of the preceding two.

"Start by setting fibnum[0] and fibnum[1], then use a loop to compute the rest of the numbers in the sequence."

The following code is an example given to us by out instructor. I ran it and I believe it can be modified to achieve the task given to us, but I am not sure how or what to change on it.



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
34
35
36
37
38
39
40
41
#define SIZE        10              
#define MAX         100              

    int             fibnum[SIZE],   
                    i,              
                    n,              
                    tally[MAX];

int main()
{   
    srand((unsigned)time(NULL));     

// INITIALIZE
    fibnum[0] = 0;
    fibnum[1] = 1;

    for (n = 0; n < MAX ; n++) {
        tally[n] = 0;
    }

// INPUT
    for (i = 0 ; i < SIZE ; i++ ) {
        n = rand() % MAX;
        fibnum[i] = n;
    }
// PROCESS
   for (i = 0 ; i < SIZE ; i++) {
        n = fibnum[i];
        tally[n] += 1;
    }
// OUTPUT
    std::cout << "Fibnum Tally" << std::endl;
    std::cout << "====== =====" << std::endl;
    for (n = 0 ; n < SIZE ; n++) {
    std::cout << std::setw(3) << n << " "
              << std::setw(5) << tally[n] << std::endl;
    }
    system("pause");

    return 0;
}
Last edited on
well, typically fib[0] = 1. The standard version is 1,1,2 ... though I suppose you can take a crack at a 0,1,1,2, ... version. Or you can skip fib[0] if you want the actual index to match the fib number (that is, index 7 is 13).

this code confuses me.
all you need is

fib[0] = fib[1] = 1;
for(index = 2; index < max; index++)
fib[index] = fib[index-1]+fib[index-2]

everything else is I/O or window dressing.
be sure to use the biggest unsigned int type you have available (typically a 64 bit) or the values will grow and overflow FAST, they are like factorials and get huge in just a few terms.

looping and computing them is brute force. you can directly compute the values, if you prefer (see golden ratio). Given the small # of terms to exceed your integer's capacity, you can also just make them a constant array.

Last edited on
1
2
3
4
5
6
7
8
9
#include <iostream>
int main()
{
   const int SIZE{20};
   int f[SIZE] = { 0, 1 };
   int *p = f, *q = p + 1, *r = p + 2, n = SIZE - 2;
   while( n-- ) *r++=*q+++*p++;
   for ( auto i : f ) std::cout << i << ' ';
}
Topic archived. No new replies allowed.