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 seem to pinpoint what's wrong with my program, the output keeps coming out as 0, 1, 1, 1, 1 and so on?
arr(i) = arr(0) + arr(1);
shouldn't that be
arr(i) = arr(i-1) + arr(i-2);
?
What your code does is the following:
arr(3) = 0 + 1
arr(4) = 0 + 1
arr(5) = 0 + 1
etc. You are assigning the same value over and over.
You need to do:
arr(i) = arr(i - 1) + arr(i - 2);
Explanation:
Say you have the array:
and i
is at index 3, this would assign arr(3) = arr(2) + arr(1)
which is 1 + 0. Therefore arr(3) = 1
i
is now at index 4, this would assign arr(4) = arr(3) + arr(2)
which is 1 + 1. Therefore arr(4) = 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With