Example 1 — Iterative Series
Print the first n Fibonacci terms using two running variables.
function printFibonacci(n) {
if (n <= 0) {
console.log("Enter a positive count of terms.");
return;
}
let a = 0;
let b = 1;
const terms = [];
for (let i = 1; i <= n; i++) {
terms.push(a);
const next = a + b;
a = b;
b = next;
}
console.log(terms.join(", "));
}
printFibonacci(8); How It Works
- Reject non-positive
nso the loop never runs with a bad count. - Seed
a = 0andb = 1— the first two Fibonacci numbers. - Each iteration stores
a(the current term). next = a + bbuilds the following term; then slide:a = b,b = next.- After
niterations you have exactlynterms in O(n) time.
