Question #145964

For this exercise, use the following 2D array, which is already declared and initialized in your programming environment below.

34 38 50 44 39
42 36 40 43 44
24 31 46 40 45
43 47 35 31 26
37 28 20 36 50
Your task is to find the average of all values in the 2D array.

Note: Be sure that your program accounts for arrays of any size, not just arrays that are 5 x 5. Your program will be tested against arrays of size n by n. It should work for any square array, not just the one shown. You should also use for loops in your program, not while loops.

Expert's answer

# We define array simple_arr as a list whose elements are lists
simple_arr = [[34, 38, 50, 44, 39],
              [42, 36, 40, 43, 44],
              [24, 31 ,46 ,40 ,45],
              [43, 47, 35, 31, 26],
              [37, 28, 20, 36, 50]]

# Create a function to calculate the average
def mean_arr(arr_arg):
    count_arr = 0
    sum_arr = 0
# Loop through all array elements with counting the number and sum of elements
    for row in arr_arg:
        for elem in row:
            count_arr += 1
            sum_arr + = elem
    res = sum_arr / count_arr
    return res
print(mean_arr(simple_arr))


LATEST TUTORIALS
APPROVED BY CLIENTS