Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Unsubscribed User
17,284 PointsWhile loop issue
What is wrong with this loop? I'm trying to achieve what is in the comments.
/*
The lion needs 4 meals per day on average to stay happy. You're going to
figure out how many days it took before the lion decided to supplement his
diet with the caretaker.
Cycle through the days in mealsPerDay. At each day, print out the average
number of meals/day the lion got since the new caretaker started.
tooHungryDay should receive the number of days before the lion started
pondering protein supplements (the first day the average dips below 4
meals)
*/
var mealsPerDay = [ 5, 4, 3, 6, 2, 4, 3, 4, 5, 1 ];
var tooHungryDay;
var runTotal;
while (i < mealsPerDay.length) {
meals = mealsPerDay[i]
day = tooHungryDay[i+1]
total = runTotal[i/10]
i++;
}
console.log(tooHungryDay);
assert(tooHungryDay, "don't forget to assign the answer to tooHungryDay");
assert(tooHungryDay < 10, "the lion is too hungry before the end of the array");
1 Answer
Hugo Paz
15,622 PointsHi Dana,
A couple of things:
You forgot to initialise the variables i, meals and day. i is actually the most important, without initialising it to 0, the loop will not work since the value of i is undefined.
I'll pot my solution, I've added the full functionality expected.
I will go through it step by step
<script>
var mealsPerDay = [ 5, 4, 3, 6, 2, 4, 3, 4, 5, 1 ];
var tooHungryDay;
var runTotal;
var i = 0;
var meals = 0;
var day = 0;
var total = 0;
while (i < mealsPerDay.length) {
meals += mealsPerDay[i];
day += 1;
console.log(meals/day);
if(meals/day < 4)
{
tooHungryDay = day;
console.error(tooHungryDay);
}
i++;
}
</script>
So first we declare the variables we need. Then we prepare the while loop.
First Cycle --
We cycle through the first element of the array, add the value to the variable meals which now is equal to 5. We then add 1 to the days the lion was feed, which is now 1. We log the average of meals per day = 5/1 which is 5. We check the condition with an if, which fails because the average is larger than 4. We increment i by one so we move to the next value in the array.
Second Cycle --
Now the meals variable has the value of 9 (5 + 4) Days is set to 2 Average is 9/2 = 4.5 so the if fails again i is incremented again and a new cycle begins.
Eventually you get the answer, day 7