0

As far as I can tell, this looks like it should work.

The first two elements are set to 1 (I am ignoring the first 0). The for loop is supposed to loop through the array, and since the fibonacci numbers are equal to the sum of the two preceeding numbers, I want to add them, then display them.

The output is all 2s, and I am not quite sure why.

Note: I am not looking directly for the answer, but a way that I can figure this out myself.

//Fibonacci sequence
#include <stdio.h>

int main(void) {
        int fib_numbers[40] = {1, 1}, i;


        for(i = 1; i < 40; i++) {
                fib_numbers[i] = fib_numbers[i] + fib_numbers[i - 1];
                printf("\t%d\n", fib_numbers[i]);
            }

        return 0;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Bowlslaw
  • 95
  • 1
  • 1
  • 3

5 Answers5

2
fib_numbers[i] = fib_numbers[i] + fib_numbers[i - 1];

You're only involving i and i-1, the Fibonacci formula involves three consecutive indices.

BTW, this:

int fib_numbers[40] = {1, 1}, i;

is horrible IMO. Please split that up in two lines.

int fib_numbers[40] = {1, 1};
int i;
Mat
  • 202,337
  • 40
  • 393
  • 406
2

After the first step, the erray element is 0 (non initialized, but 0 in this case). What about fib[i+1] = fib[i]+fib[i-1]; printf ("%d\n",fib[i+1])? And of course fib must have size of 41 instead of 40.

Giuseppe Guerrini
  • 4,274
  • 17
  • 32
2

Check out the left side of this line of the code

fib_numbers[i] = fib_numbers[i] + fib_numbers[i - 1];

and consider where in the array you are storing the value.

Lucas
  • 13,679
  • 13
  • 62
  • 94
0

Update code as follows:

for(i = 2; i < 40; i++) {
                fib_numbers[i] = fib_numbers[i-1] + fib_numbers[i - 2];
                printf("\t%d\n", fib_numbers[i]);
            }
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
0

I guess your loop is wrong

  for(i = 1; i < 40; i++) {
       fib_numbers[i] = fib_numbers[i] + fib_numbers[i - 1];
       printf("\t%d\n", fib_numbers[i]);
  }

You are assigning i'th element by overriding itself. Value of i'th element is null when i is greater than 1.

May be you should do it like this

//Fibonacci sequence
#include <stdio.h>

int main(void) {
    int fib_numbers[40] = {1, 1};

    for(int i = 2; i < 40; i++) {
        fib_numbers[i] = fib_numbers[i - 1] + fib_numbers[i - 2];
        printf("\t%d\n", fib_numbers[i]);
    }

    return 0;
}

But I recommend using recursion to find fibonacci.

//Fibonacci sequence
#include <stdio.h>

int main void() {

   int fib_numbers[40] = {1, 1};

   for(int i = 2 ; i < 40 ; i++) {
        fib_numbers[i] = fibonacci(i);
        printf("\t%d\n", fib_numbers[i]);
   }
   return 0;
}

int fibonacci(int a) {
     if (a <= 1) return 1;
     return fibonacci( a - 1 ) + fibonacci( a - 2 );
}
WarFox
  • 4,933
  • 3
  • 28
  • 32