Fibonacci wrong conclusion? (WITH)

int * fibonacci(int n) { int range = n + 1; int * arr = malloc(range * sizeof(int)); arr(0) = 0; arr(1) = 1; for(int i = 2; i < range; ++i) { arr(i) = arr(0) + arr(1); } return arr; } 

I can’t determine exactly what is wrong with my program, the output continues to be displayed as 0, 1, 1, 1, 1, and so on?

+4
source share
2 answers
 arr(i) = arr(0) + arr(1); 

must not be

 arr(i) = arr(i-1) + arr(i-2); 

?

+5
source

What does your code do:

 arr(3) = 0 + 1 arr(4) = 0 + 1 arr(5) = 0 + 1 

etc .. You assign the same value over and over.

You need to do:

  arr(i) = arr(i - 1) + arr(i - 2); 

Explanation:

Let's say you have an array:

  • arr (1) = 0
  • arr (2) = 1

and i is in index 3, this assigns arr(3) = arr(2) + arr(1) equal to 1 + 0. Therefore, arr (3) = 1

i now at index 4, this will assign arr(4) = arr(3) + arr(2) , which is 1 + 1. Therefore, arr (4) = 2

+5
source

All Articles