Wednesday, May 26, 2021

Javascript Practice 66: JS Hero - Loops and arrays

 
Question: 

Write a function mean that accepts an array filled with numbers and returns the arithmetic mean of those numbers.

Example: mean([1, 2, 3]) should return (1+2+3)/3 = 2.




Answer: 

function mean (arr) { 

let sum = 0; 
for (let i = 0; i < arr.length; i++) { 

sum = sum + arr[i]; 

return sum / arr.length
}





> we declare a function mean
> it has one parameter 'arr'
> we declare a variable sum and initialize it with a value of 0
> we first use the for loop to add up all the elements of an array 
> first expression: let i = 0
> second expression or condition: i < arr.length
> third expression: i++ (i++ is identical to i = i + 1)
> loop code: sum = sum + arr[i]
> to understand this for loop, we call the function mean with an arr of 3 elements
> [1, 2, 3] 
> in the start expression ' i ' is initialized with a value of 0
> this means that 0 < 3; hence the loop code is executed
> sum = sum + arr[0]; ∴ sum = 0 + 1 = 1 (as index 0 of arr is 1)
> in the final or third expression i is increased by 1 (0 + 1 = 1)
> this means that 1 < 3, hence the loop code is executed
> sum = sum + arr[1]; ∴ sum = 1 + 2 = 3 (as index 1 of arr is 2)
> in the final or third expression i is increased by 1 (1 + 1 = 2)
> this means that 2 < 3, hence the loop code is executed
> sum = sum + arr[2]; ∴ sum = 3 + 3 = 6 (as index 2 of arr is 3)
> in the final or third expression i is increased by 1 (2 + 1 = 3)
> now 3 < 3 is no longer fulfilled 
> the loop is terminated and the program execution continues after the loop 
> in this case the program executes and returns the 'sum' variable to us
> we divide the returned sum variable by the length of the array
> our code example has added all the elements in an array and divided it by the length of the array
> hence we get the mean of the array

No comments:

Post a Comment