I'm really surprised if this question isn't a duplicate, but since I failed to find one that asked about the Fibonacci sequence rather than someone using it as an example, I'll answer.
The most natural approach, besides using the built-in Fibonacci
function, recursion:
f[0] = 0; f[1] = 1;
f[n_] := f[n] = f[n - 1] + f[n - 2] (* note memoization *)
Array[f, 10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
Better performing may be Nest
and NestList
:
fibonacciList[n_] := Module[{x = 0}, NestList[x + (x = #) &, 1, n - 1]]
fibonacciList[10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
Another useful way uses LinearRecurrence
:
LinearRecurrence[{1, 1}, {1, 1}, 10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
Hopefully these examples inspire you.
I now note that you request the sequence starting from zero. Most of these are easy to adapt or modify. The first one is simply:
Array[f, 10, 0]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}
For the second you may instead write:
fibonacciList2[n_] := Module[{x = 1}, NestList[x + (x = #) &, 0, n - 1]]
fibonacciList2[10]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}
The last one merely needs the proper seed:
LinearRecurrence[{1, 1}, {0, 1}, 10]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}
Finally, taking the question at face value you can modify your code to return fPrev
rather than fNext
to start from zero:
fibonacciSequence[n_] :=
Module[{fPrev = 0, fNext = 1, i = 0},
While[i++ < n, {fPrev, fNext} = {fNext, fPrev + fNext}];
fPrev
]
Array[fibonacciSequence, 10, 0]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}
Addendum for rcollyer:
$fibList = {0, 1};
fibonacciList[n_] /; n <= Length@$fibList := Take[$fibList, n]
fibonacciList[n_] := $fibList =
$fibList ~Join~
Module[{x = $fibList[[-2]]},
Rest@NestList[x + (x = #) &, $fibList[[-1]], n - Length@$fibList]]
Array[Fibonacci, 15]
orFibonacci @ Range @ 15
myself. $\endgroup$