Trouble using a for loop to get the average of numbers in an array

i am just learning and am having some issues understanding functions and loops. i am attempting to make a function to get the average of the numbers entered into an array .i was able to do it using a for of loop

function avg(arr) {
let total = 0;
for (let num of arr) {
total += num;
}
let result = total / arr.length;
return result;
}

i am trying to get a better understanding of what im doing so i am trying different methods and am not seeing what i am doing wrong using a for loop
, all this does is add .5 for each number in the array.

function avg(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += i;
}
return total / arr.length;
}

In the second version of your code, you are adding i, but I think you want to be adding the value in the array arr at index i.

1 Like

you are awesome!

function avg(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total / arr.length;
}

the corrected code works now!

1 Like