Covering Losses (Loop)


#1

This is the exercise I am referring to: https://www.codecademy.com/courses/introduction-to-javascript/0/5#

Apparently, what is pasted below is CORRECT and was accepted by the system, but I cannot fully understand why. First I will show the entire coded exercise and then I will ask specific questions beneath the code:

//To make up the money you lost from picking rotten strawberries,
//you decide to pick 10 extra strawberries everyday for the next
//7 days.

//Your earnings
var earnings = 0;

//Fill in the outer loop with an inner loop that loops through
//10 strawberries and increment your earnings by 2.25 for every
//extra strawberry that you pick
for (var days = 7; days > 0; days–)
{
_ //Insert inner for loop here_
for (var extraBerries = 0; extraBerries < 10; extraBerries++) {
earnings += 2.25;
}
}

//Boolean that returns true if your losses have been covered
var lossesCovered = true;

//Write an if statement that changes the lossesCovered to true
//if the earnings are greater than or equal to 225
var lossesCovered = true;
if (earnings >= 225) {
lossesCovered = true;
}
var lossesCovered = earnings >= 225;
console.log('Are losses covered? ', earnings >= 225 ? ‘Yeah’ : ‘No’);

A few questions about some of the bold code above:

  1. Why is it correct for “days–” and “extraBerries++”?
  2. Shouldn’t “extraBerries < 10” instead be “extraBerries <= 10”?

#2

The above is a wind down loop, hence the downward direction (decrement).

If it started at 1 that would be the case, however since it starts at 0, nine steps takes it to 9, not 10, hence < 10. There will still be ten iteations of the loop.


#3

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