Find Mean from Median and Mode of an Array in C++



Mean, Median, and Mode are key statistical measures that help in describing a dataset's central tendency and distribution. These quantities help in understanding the central tendency and distribution of the given data. In this article, we will learn how to find the Mean if the Median and Mode of a given array are known in C++.

Problem Statement

We are given an array of numbers, and we need to find the mean if the median and mode are provided in C++.

Example

    Input:

    [5, 15, 25, 35, 35, 40, 10]
    Median = 25
    Mode = 35

    Output:

    Mean = 20

Brute Force Approach

In this approach, we calculate the mean by traversing the array. The mean is calculated by finding the sum of all the elements in the array and dividing it by the number of elements.

Steps

  • Traverse the array and calculate the sum of all elements.
  • Divide the total sum by the number of elements to find the mean of the array.
  • Return the mean of the array.

Implementation Code

#include 
using namespace std;

// Function to calculate mean
double calculateMean(int arr[], int n) {
    double sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum / n;
}

int main() {
    int arr[] = {5, 15, 25, 35, 35, 40, 10};
    int n = 7;
    double mean = calculateMean(arr, n);
    cout << "The Mean of the given dataset is: " << mean << endl;
    return 0;
}
    
Output:
The Mean of the given dataset is: 23.5714
    
Time Complexity: O(n), as we are traversing the array.
Space Complexity: O(1), constant space.

Optimized Approach

In the optimized approach, we find the mean using the formula directly, without traversing the array. The formula to find the mean using the median and mode is:

Mean = (Mode + 2 × Median) / 3

We can simply use this formula to find the mean if the median and mode are known.

Steps

  • Define a function to find the mean using the formula.
  • This function will take the median and mode as arguments and compute the mean.

Implementation Code

#include 
using namespace std;

// Function to calculate mean using mode and median
double calculateMean(double median, double mode) {
    return (mode + 2 * median) / 3;
}

int main() {
    double median, mode;
    cout << "Enter the median of the array: ";
    cin >> median;
    cout << "Enter the mode of the array: ";
    cin >> mode;

    double mean = calculateMean(median, mode);
    cout << "The Mean of the array is: " << mean << endl;

    return 0;
}
    
Output:
Enter the median of the array: 25
Enter the mode of the array: 35
The Mean of the array is: 20
    
Time Complexity: O(1), constant time.
Space Complexity: O(1), constant space.
Updated on: 2024-11-13T17:55:16+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements