# Lesson goal: Using arrays to average numbers

Previous: Loops and arrays | Home | Next: Arrays and recurrence relations

In a past lesson, you learned how to use a while-loop to read in numbers and compute their average. The issue with that lesson is that the original numbers (i.e. the data) was lost! You have the average, but not the numbers that gave the average!

Since arrays can store multiple values, let's revisit taking the average of some numbers, while retaining the original numbers. Note the new construct here is the nums={} line, which tells the comptuer that variable nums is to be an array, but is empty as the program starts, hence the ={}, or "let nums be equal to an empty array right now."

# Now you try. See the pink box for 3 fixes this code needs. Can you get it running?

This code will not run! Three fixes are needed that hopefully will help you understand arrays.
1. The if x>= 0 then line sees if the number that the user has typed is $\ge 0$. If so, this means keep recording numbers. In this first fix, what line would you put right under this if statement to set the $i^{th}$ element of the array called nums equal to x, which is the number the user just typed?
2. Take a look at the first for i=1,#nums do line. This is a loop that will count over all element positions of the array called nums. Recall that in computing an average we have to add all numbers to be averaged together. We are computing this sum in the variable called sum. How would you fix the sum=sum+???? line to add the value in the $i^{th}$ element of array nums to the variable sum?
3. Look at the very last print statement in the code. Here we want to show the user that we still have a record of the numbers they typed. What would you put in this print statement to display the $i^{th}$ element of the array called nums?

Can you make these fixes? Dismiss.

Show a friend, family member, or teacher what you've done!