Curiosity
Curiosity

Reputation: 33

While loop not stopping correctly

I'm trying to create a simple Fibonacci sequence program. My while loop doesn't stop correctly when the condition is met. For example, when num=10, my while loop doesn't end until counter===13. Am I misunderstanding something about while loops?

let counter = 2; 
let sum = [1,1];
let i = 1;
let num = 10;

while(counter<num) {
   counter=sum[i-1]+sum[i];
   sum.push(counter);
   i++;
   console.log(counter + ' ' + num);
}

Upvotes: 3

Views: 1177

Answers (2)

Max Shouman
Max Shouman

Reputation: 1331

The problem here is that counter is actually changed only after the while condition is checked; so when it's equal to 8 (the sum of the last two values: 5 and 3), a last iteration can be performed, in which counter becomes 13 (8 + 5).

If you want to prevent it from exceeding 10, you can put the condition after the value modification and interrupt the loop if it's not met:

while(true) {
   counter=sum[i-1]+sum[i];
   if (counter >= 10) {
      break;
   }
   sum.push(counter);
   i++;
   console.log(counter + ' ' + num);
}

However, there are simpler ways to develop a Fibonacci series, such as recursive methods.

Upvotes: 1

Dakota Lee Martinez
Dakota Lee Martinez

Reputation: 621

Setting up a little test like this can be helpful to visualize what's going on.

let counter = 2;
let sum = [1, 1];
let i = 1;
let num = 10;

while (counter < num) {
  counter = sum[i - 1] + sum[i];
  sum.push(counter);
  i++;
  console.log(
    `counter: ${counter}, i: ${i}, num: ${num}, sum: ${sum}, counter < num: ${
      counter < num
    }`
  );
}

If you do this, you'll see the following:

counter: 2, i: 2, num: 10, sum: 1,1,2, counter < num: true 
counter: 3, i: 3, num: 10, sum: 1,1,2,3, counter < num: true 
counter: 5, i: 4, num: 10, sum: 1,1,2,3,5, counter < num: true 
counter: 8, i: 5, num: 10, sum: 1,1,2,3,5,8, counter < num: true 
counter: 13, i: 6, num: 10, sum: 1,1,2,3,5,8,13, counter < num: false 

The loop will exit when the condition is checked and the result is false. So, the counter will actually change after the last time the condition is true. When counter becomes equal to 13, the condition will no longer be true and after it is checked again, the loop will exit.

Upvotes: 2

Related Questions