In the last episode, you learned about lists. Now its time to put your new found knowledge to the test. In this challenge, I want you to create a list called grades. The grades should be 82, 76, 88, and 92. I want you store those values in the list, then calculate the average of the values. Pause the video and give it a shot.
How’d that go for you? Feel free to follow along. Now keep in mind, there are lots of ways to do the same thing in programming so your solution may look different than mine. Let’s start by creating a new list.
const grades = [82, 76, 88, 92];
Now at this point, we should add the total.
var sum = grades[0] + grades[1] + grades[2] + grades[3];
Now lets determine the average.
var average = grades / 4;
And that’s it. Let’s print out the results.
print('the average is $average');
And with that, we have an average of 84.5. But thinks are just getting started.
Okay, so how’d that go for you? Well, I have another challenge for you. We used brackets to get the first and last item in the list, but we have properties as well. I want you to replace the brackets with properties instead. Use the first property and the last property. Finally, when you divide to determine the average, use the length property. Pause the video and give it a shot.
Okay, we’ll start with the sum variable. Instead of using grades[0], let’s change that to the first item in the grades list.
var sum = grades.first + grades[1] + grades[2] + grades[3];
Now do the same for the last element. This time, instead of using grades[3], let’s use last instead.
var sum = grades.first + grades[1] + grades[2] + grades.last;
Finally, let’s update the average to use the length of list.
var average = sum / grades.length;
Believe it our not - that’s it. We’re using properties in place hard coding values, but we get the same result. Nice work.