
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
#includeOutput: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; }
The Mean of the given dataset is: 23.5714Time 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
#includeOutput: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; }
Enter the median of the array: 25 Enter the mode of the array: 35 The Mean of the array is: 20Time Complexity: O(1), constant time.
Space Complexity: O(1), constant space.