Some of the exercises for loops make sense form me, others I am just guessing on the answers but with no comprehension.

This exercise I was able to feel in the blanks for but do not understand it:

Complete the code blocks such that the value of collectedHarvest will be 305 after the code block executes:

let temp = 35;
let collectedHarvest = 5;
while (temp > 5) {
collectedHarvest += 100;
temp -= 10;

So, you have a while loop. That keeps running as long as the condition is met.

That means it will keep doing the stuff in the while loop as long as temp is greater than 5.

In the for loop, it will add 100 to the collectedHarvest, and reduce the temp by 10.

If you want this to end up with the collectedHarvest at 305, and it is starting at 5, then you need to run through that loop three times, as it adds 100 each time.

So you need a temp that will become less than 5 after you do the stuff in the loop three times. After that it won’t be greater than 5 any more, so the while condition won’t be true.

So you need it to be something where taking ten away three times makes it less than five, but taking ten away twice doesn’t.

That means any value from 26 to 35 will work.

With 35, it checks the value is over 5. It is, so it runs the while loop for the first time.
collectedHarvest now becomes 105, temp becomes 25.

It checks if 25 is greater than 5. It is, so it runs the while loop for the second time.
collectedHarvest now becomes 205, temp becomes 15.

It checks if 15 is greater than 5. It is, so it runs the while loop for the third time.
collectedHarvest now becomes 305, temp becomes 5.

It checks if 5 is greater than 5. It isn’t, so the loop ends.

1 Like