// This program calculates stats of movie goers in a month
//It calculates mean, median and mode
#include <iostream>
#include <iomanip>
usingnamespace std;
double calculateMean(int *, int);
double calculateMedian(int *, int);
int calculateMode(int *, int);
int main()
{
int *nums;
int num_students;
char repeat = ' ';
do
{
cout << "Enter in how many students were surveyed: ";
cin >> num_students;
while (num_students < 0)
{
cout << "Invalid number of students. Enter a positive integer.\n";
cout << "Enter in how many students were surveyed: ";
cin >> num_students;
}
nums = newint[num_students];
for (int count = 0; count < num_students; count++)
{
cout << "Number of movies viewed by Person #" << (count + 1) << ": ";
cin >> nums[count];
while (nums[count] < 0)
{
cout << "Please enter in a positive number: ";
cout << "\nNumber of movies viewed by Person #" << (count + 1) << ": ";
cin >> nums[count];
}
}
cout << fixed << showpoint << setprecision(1);
cout << "\nThe mean is: ";
cout << calculateMean(nums, num_students) << endl;
cout << "\nThe median is: ";
cout << calculateMedian(nums, num_students) << endl;
cout << "\nThe mode is: ";
cout << calculateMode(nums, num_students) << endl;
delete[] nums;
nums = 0;
cout << "Do you want to try again? ";
cin >> repeat;
} while (repeat == 'Y' || repeat == 'y');
cout << "Program ending.\n";
return 0;
}
double calculateMean(int *nums, int num_students)
{
double total = 0;
double average;
for (int count = 0; count < num_students; count++)
{
total += nums[count];
}
average = total / num_students;
return average;
}
double calculateMedian(int *nums, int num_students)
{
double median = 0.0;
cout << fixed << showpoint << setprecision(1);
if (num_students % 2 == 0)
{
median = (nums[num_students / 2] + nums[(num_students / 2) + 1]) / 2.0;
}
else
median = nums[num_students / 2];
return median;
}
int calculateMode(int *nums, int num_students)
{
int mode = 0;
int val = 0;
int index;
for (index = 0; index < num_students; index++)
{
if (*(nums + index) == *(nums + (index + 1)))
{
mode++;
val = *(nums + index);
}
}
if (val > 0)
return val;
elsereturn -1;
}
Put the code you need help with here.
For mode, you have to think pairs; a value and how many times it occurs. You should have one pair for each unique value. A set like {2,5,3,3,7,2,5} is multi-modal, because 2, 3, and 5 each occur twice, and therefore the set has not one, but three modes.