C++ Program to Find the Median of Numbers

«
»
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.

  1. /*
  2.  * C++ Program to Compute the Median of Numbers
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7.  
  8. int main()
  9. {
  10.     std::vector<double> v;
  11.     int temp, len;
  12.  
  13.     std::cout << "Enter the number of elements ";
  14.     std::cin >> len;
  15.     while (v.size() < len)
  16.     {
  17.         std::cin >> temp;
  18.         v.push_back(temp);
  19.     }
  20.     sort(v.begin(), v.end());
  21.     if (v.size() % 2 == 0)
  22.         std::cout << std::endl << "Median = "
  23.                   << (v[v.size()/2 - 1] + v[v.size()/2]) / 2
  24. 	          << std::endl;
  25.     else
  26.         std::cout << std::endl << "Median = " << v[v.size()/2]
  27. 		  << std::endl;
  28. }

$ 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.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.