find the average of all elements in an array in python
Code snippet on how to find the average of all elements in an array in python
#declare an array and assign to it some values
arr=[1,2,4,6,8]
#calculate sum of all array elements
sum=0
for i in range(0,len(arr)):
sum=sum+arr[i]
#Find average of array elements
average=sum/len(arr)
print(average)
This code finds the average of all elements in an array. First, an array is declared and some values are assigned to it. Then, a variable ‘sum’ is declared and set to 0. A for loop is used to iterate through the array and add each element to the sum variable. After summing all of the elements in the array, the average is found by dividing the sum by the number of elements in the array. The average is then printed to the console.