Home > Back-end >  How to I add a counter to this while loop
How to I add a counter to this while loop

Time:11-10

I need to add a counter to my while loop, so that I can know how many times the loop iterated.

var popSize = 100;
var endSize = 200;

var x = popSize / 3;     
var y = popSize / 4;     

while (popSize < endSize) 
{
    popSize = popSize   x - y; 
    popSize  ;        
}
console.log(popSize);

CodePudding user response:

Store the iterations in a variable and increment it inside the loop:

var popSize = 100;
var endSize = 200;

var iterations = 0
var x = popSize / 3;
var y = popSize / 4;

while (popSize < endSize) {
  iterations  ;
  popSize = popSize   x - y;
  popSize  ;
}
console.log(popSize);
console.log('iterations', iterations)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

var counter = 0;

while (popSize < endSize) 
{
    popSize = popSize   x - y; 
    popSize  ;        
    counter  ;
}

console.log(counter);
  • Related