How to calculate median?

I am new to cpp and I am trying to calculate the median of an array. The user decides how many items are in the array, and inputs the values. Then I need to calculate average, median, and mode. I have the average part done. I am stuck trying to figure out how to calculate median. Anyone have advice on where to start? Or a page to read? I searched the forum already and couldn't figure it out from previous posts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Unit 9.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

int main()
{
	// Get number of students from user.
	int getStudents;
	cout << "How many students were surveyed? ";
	cin >> getStudents;

	// Creating array "setMovies" with size of getStudents using pointer.
	int *setMovies;
	setMovies = new int[getStudents];

	// Storing the amount of movies each student watched into setMovies array.
	for (int i = 0; i < getStudents; i++)
	{
		cout << "How many movies did each student watch: ";
		cin >> setMovies[i];
	}

	int sum = 0;
	for (int i = 0; i < getStudents; i++)
	{
		sum += setMovies[i];
		
	}
	int average = sum / getStudents;
	cout << "The average is: " << average << endl;

	for (int i = 0; i < getStudents; i++)
	{
		for (int j = i + 1; j <getStudents; j++)
		{
			if (setMovies[i]>setMovies[j])
			{
				int temp = setMovies[i];
				setMovies[i] = setMovies[j];
				setMovies[j] = temp;
			}
		}
		cout << setMovies[i] << " ";
	}
	

    return 0;
}

the hard way, sort the array then report the middle value

the sloppy way:

find the highest & lowest numbers. If they're different, "erase" the highest.
If they're the same, thats your answer.
find the highest & lowest numbers. If they're different, "erase" the lowest this time instead.
If they're the same, thats your answer.

"erase" in this case could be setting a -1 in the array since the values are expected to be positive. just remember to ignore negatives when finding the lowest value if you do this.

There's other ways to do it too.

Last edited on
I agree with above. Sorting and finding the middle value is definitely an option for finding the median. Also consider that you might have an even numbered array and in that case you need to take the 2 middle values and take the average of them and that would be your median.
Sorting via using std if you wish, there are many types of sorting methods: http://www.cplusplus.com/articles/NhA0RXSz/

The mode is the number that appears most often in the array. You can find this by looping through your array to find the element that appears the most.


Yeah if you're in a class write the sort code. you're gonna use it again later in the semester anyway.
Topic archived. No new replies allowed.