I have a homework problem that requires that I write a program that gathers statistical data about the number of movies students see in a month. The program should perform the following steps.
A) Ask the user how many students were surveyed. An array of integers with this many elements should then be dynamically allocated.
B) Allow the user to enter the number of movies each student saw into the array.
C) Calculate and display the average, and median of the values entered.
Input Validation: Do not accept negative numbers for input.
Okay I am new to programming and having trouble getting some of it. So it might not be the most efficient or pretty set up but what I have so far performs all the required functions the one trouble spotting I am having is that I think I need a loop for the last part about the not accepting negative input but I am not sure how to add it in, if someone could please help me with that, thank you.
#include <iostream>
usingnamespace std;
int findMedian (int [], int);
int main ()
{
int *students, // dynamically allocate an array '*movies'
total = 0, //accumulator
average; // hold average movies seen
int numStudents, // holds number of students surveyed 'n'
count; // counter variable
int j, temp;
// Get number of students surveyed
cout << "How many students were surveyed? ";
cin >> numStudents;
// dynamic allocation array
// students surveyed
students = newint[numStudents];
// number of movies students saw
cout << "Enter number of movies each student saw in one month.\n";
for (count = 0; count < numStudents; count++)
{
cout << "student #" << (count +1) << ": ";
cin >> students[count];
}
// sort dynamically allocated array
for (count = 0; count < numStudents; count++)
{
for (j = count + 1; j < numStudents - 1; j++)
{
if (students[count] > students[j])
{
temp = students[count];
students[count] = students[j];
students[j] = temp;
}
}
}
// calculated average movies seen
for (count = 0; count < numStudents; count++)
{
total += students[count];
}
average = total / numStudents;
//display results
cout << "Students saw " << average << " movies on average.\n";
int median = findMedian (students, numStudents);
cout << "the median is" << median << " .\n";
return 0;
}
int findMedian (int numbers[], int size)
{
int median;
if (size % 2 == 0)
median = (int)(numbers[size / 2] + numbers[size / 2 - 1])/2;
else
median = numbers[size / 2];
return median;
}