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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With