This C++ program computes the median of the given set of numbers. The program takes the count of numbers that are to be input, the elements are input and stored in a vector and sorted. The median of the elements is computed accordingly, i.e. if the count of the numbers is even, the average of the middle and one more than middle element is computed otherwise the middle element’s value is computed. This computed value is the median of the given set of numbers.
Here is the source code of the C++ program computes the median of the given set of numbers. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Compute the Median of Numbers
*/
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<double> v;
int temp, len;
std::cout << "Enter the number of elements ";
std::cin >> len;
while (v.size() < len)
{
std::cin >> temp;
v.push_back(temp);
}
sort(v.begin(), v.end());
if (v.size() % 2 == 0)
std::cout << std::endl << "Median = "
<< (v[v.size()/2 - 1] + v[v.size()/2]) / 2
<< std::endl;
else
std::cout << std::endl << "Median = " << v[v.size()/2]
<< std::endl;
}
$ a.out Enter the number of elements 10 1 2 3 4 5 6 7 8 9 10 Median = 5.5 $ a.out Enter the number of elements 5 1 2 3 4 5 Median = 3
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Programming MCQs
- Check Computer Science Books
- Check C++ Books
- Practice Computer Science MCQs
- Check Programming Books