Tabbie C
Tabbie C

Reputation: 3

why is the for loop not running?

I'm supposed to create a function that will continue to double the first argument until it is greater than or equal to the 2nd argument. Every time it doubles, I add 20 to a counter.

However, for whatever reason, it doesn't seem to be adding 20 to the counter as it always returns 0 and does not print the console.log I included for each loop, which makes me think it's not running the loop.

Why isn't it running the loop and what am I doing wrong?

function bacteriaTime(currentNum, targetNum) {
  let counter = 0
  for (let i = currentNum; i >= targetNum; i *= 2) {
    counter += 20;
    console.log('bacteria count is ' + i + ' and ' + counter + ' have passed.')
  }
  return counter;
  console.log(counter);
}

Upvotes: 0

Views: 198

Answers (2)

Derek C.
Derek C.

Reputation: 998

Seems like you've mixed up your comparison. In your for loop you had i >= targetNum which with your inputs would almost always be false. Simply switch the operator to <= as below and you should be good. This will mean i is less than targetNum.

function bacteriaTime (currentNum,targetNum){
    let counter = 0
    for (let i = currentNum; i <= targetNum; i *= 2){
        counter += 20;
        console.log ('bacteria count is ' + i + ' and ' + counter+ ' have passed.')
        }
    console.log(counter);
    return counter;
}

Hope that works. It was probably just a simple mix up.

Upvotes: 0

bedranfleck
bedranfleck

Reputation: 165

You might wanna check if your condition wasn't already met, and therefore, the code has returned. Also your condition is backwards. It should be: for (let i = currentNum; i <= targetNum; i *= 2) {

Upvotes: 1

Related Questions