You must know how to perform basic operations on an array like finding the sum of elements of an array, finding the product of elements of an array, reversing an array, finding the largest and smallest element in an array, etc. to be fully prepared for coding interviews.
In this article, you’ll learn how to find the mean of an array using Python, C++, JavaScript, and C.
Problem Statement
You’re given an array arr. You need to find the mean of arr.
Example 1: Let arr = [1, 2, 3, 4, 5, 6, 7, 8]
Mean of arr = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8) / 8 = 4.5
Thus, the output is 4.5.
Example 2: Let arr = [1, 1, 1, 1, 1, 1]
Mean of arr = (1 + 1 + 1 + 1 + 1 + 1) / 6 = 1
Thus, the output is 1.
Formula to find the mean of an array:
Mean of an array = sum of all elements of the array / total no. of elements in the array
Approach to Solve the Problem
You can find the mean of an array by following the approach outlined below:
Initialize a variable sumOfElements (with a value of 0) to store the sum of all elements in the array. Iterate through the array and add each element of the array with sumOfElements. Finally, return sumOfElements / sizeOfArray.
C++ Program to Find the Mean of an Array
Below is the C++ program to find the mean of an array:
Output:
Python Program to Find the Mean of an Array
Below is the Python program to find the mean of an array:
Output:
JavaScript Program to Find the Mean of an Array
Below is the JavaScript program to find the mean of an array:
Output:
C Program to Find the Mean of an Array
Below is the C program to find the mean of an array:
Output:
Solve Problems Based on Arrays
Arrays are one of the most asked topics in programming interviews. It’s wise to practice some of the most common problems based on arrays like finding the maximum and minimum elements of an array, finding the product of all elements in an array, removing duplicate elements from an array, reversing an array, sorting an array, etc. if you’re serious about getting a job in the programming field.