Program for Mean and median of an unsorted array in C++

Given with an array of an unsorted array and the task is to calculate the mean and median of an unsorted array.

For calculating the mean

Mean is calculated for finding out the average. We can use the given formula to find out the mean

Mean = (sum of all the elements of an array) / (total number of elements

For calculating the median

If an array is sorted, median is the middle element of an array in case of odd number of elements in an array and when number of elements in an array is even than it will be an average of two middle elements.

If the array is not sorted first task is to sort the array and then only the given logic can be applied

If n is odd

1, 2, 3, 4, 5
Median = 3

If n is even

1, 2, 4, 5
Median = (2 + 4) / 2 = 3

Input

arr[] = {3,5,2,1,7,8}

Output

Mean is : 4.33333
Median is : 4

Input

arr[] = {1, 3, 4, 2, 6, 5, 8, 7}

Output

Mean is: 4.5
Median is: 4.5

Algorithm

Start
Step 1→ declare function to calculate mean
double mean(int arr[], int size)
declare int sum = 0
Loop For int i = 0 and i < size and i++
Set sum += arr[i]
End
return (double)sum/(double)size
Step 2→ declare function to calculate median
double median(int arr[], int size)
call sort(arr, arr+size)
IF (size % 2 != 0)
return (double)arr[size/2]
End
return (double)(arr[(size-1)/2] + arr[size/2])/2.0
Step 3→ In main()
Declare int arr[] = {3,5,2,1,7,8}
Declare int size = sizeof(arr)/sizeof(arr[0])
Call mean(arr, size)
Call median(arr, size)
Stop

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//calculate mean
double mean(int arr[], int size){
int sum = 0;
for (int i = 0; i < size; i++)
sum += arr[i];
return (double)sum/(double)size;
}
//calculate median
double median(int arr[], int size){
sort(arr, arr+size);
if (size % 2 != 0)
return (double)arr[size/2];
return (double)(arr[(size-1)/2] + arr[size/2])/2.0;
}
int main(){
int arr[] = {3,5,2,1,7,8};
int size = sizeof(arr)/sizeof(arr[0]);
cout << "Mean is : " << mean(arr, size)<<endl;
cout << "Median is : " << median(arr, size) << endl;
return 0;
}

Output

If run the above code it will generate the following output −

Mean is : 4.33333
Median is : 4