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.
// Unit 9.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
usingnamespace 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 = newint[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.
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.