Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop not stopping correctly

Tags:

javascript

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);
}
like image 919
Curiosity Avatar asked Apr 22 '26 19:04

Curiosity


1 Answers

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.

like image 85
Dakota Lee Martinez Avatar answered Apr 24 '26 07:04

Dakota Lee Martinez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!