Looping through strawberries divisible by 5


#1

https://www.codecademy.com/courses/introduction-to-javascript/0/3#

Oops, try again. Your value for goodStrawberries is incorrect. Check your arithmetic and your loop bounds.

The value I’m getting in the console is 416; I’m not sure what I’m doing wrong here…

//You have 500 good strawberries, indexed from 1 to 500
var goodStrawberries = 500;

//For every strawberry whose index is divisible
//by 5, decrement the value of goodStrawberries by 1
for (var i=0; i<goodStrawberries; i++){
    if(i % 5 === 0){
        goodStrawberries -= 1;   
    }
}

console.log(goodStrawberries);

#2

The above code is decrementing the variable in the conditional so it ends the loop prematurely.

var goodStrawberries = 500;

for (var i = 1, j = goodStrawberries; i <= j; i++) { ... }

In the above we copy the value of goodStrawberries into a variable that does not change while the loop runs. This will give the correct result.


#3

That did it, thanks so much!!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.