HGB
HGB

Reputation: 2193

Fibonacci sequence Javascript do while loop

I have been going through various threads and languages on this topic but I do not seem to find a solution for setting a bar for a fibonacci sequence to stop below 100 with a do while loop in Javascript.

var fbnci = [0, 1];
var i = 2;

do {
   // Add the fibonacci sequence: add previous to one before previous
   fbnci[i] = fbnci [i-2] + fbnci[i-1];
   console.log(fbnci[i]);
   fbnci[i]++;
} 
while (fbnci[i] < 100);

For some reason, the code above only runs once. What should I set the while condition to in order to keep printing the result until it reaches the closest value to 100?

Upvotes: 1

Views: 3423

Answers (3)

Divyanth Jayaraj
Divyanth Jayaraj

Reputation: 960

The loop occurs only once because by the time i=3, your while condition is not able to check if fbci[3] < 100 since fbnci[3] is undefined.

You can do this instead

var fbnci = [0, 1];
var i = 1;
while(fbnci[i] < 100) {
  fbnci.push(fbnci[i] + fbnci[i-1]);
  i++;
}

console.log(fbnci);

Upvotes: -1

PolishDeveloper
PolishDeveloper

Reputation: 950

You have an error in the code, it should be :

var fbnci = [0, 1], max = 100, index = 1, next;
do {
  index++;
  next = fbnci[index-2] + fbnci[index-1];
  if (next <= max) {
      console.log(next);
      fbnci[index] = next;
  }
} while(next < max);

Solution that prints all fib numbers that are lower than max.

Upvotes: 2

Tommy Steimel
Tommy Steimel

Reputation: 791

For me, it is an infinite loop that keeps printing out 1. You need to increment i instead of incrementing fbnci[i]:

i++ instead of fbnci[i] ++

Additionally, you'll still fail the while condition, since you're checking a nil value. You'll want to change your while to check fbnci[i-1]:

} while(fbnci[i-1]<100);

Upvotes: 1

Related Questions