Write a program that can be used to gather statistical data about the number of
ID: 3600264 • Letter: W
Question
Write a program that can be used to gather statistical data about the number of movies college 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. You will be using pointers for this program!!!
B) Allow the user to enter the number of movies each student saw into the array.
C) Calculate and display the average, median, and mode of the values entered (see below). In statistics, when a set of values is sorted in ascending or descending order, its median is the middle value.
If the set contains an even number of values, the median is the mean, or average, of the two middle values. The mode of a set of values is the value that occurs most often or with the greatest frequency. Input Validation:
Do not accept negative numbers for input.
Explanation / Answer
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <map>
using namespace std;
int main()
{
int numOfStudents,i,val,left,right,mode;
map<int,int> m;
cout<<"Enter the number of students surveyed : ";
cin>>numOfStudents;
int *arr=(int *)malloc(numOfStudents*sizeof(int));
for(i=0;i<numOfStudents;i++)
{
cout<<"Enter number of movies student "<<i+1<<" saw : ";
cin>>val;
m[val]++; //Storing frequency of each element in map
*(arr+i)=val;
}
sort(arr,arr+numOfStudents);
int sum=0;
float avg,median;
for(i=0;i<numOfStudents;i++)
{
sum+=*(arr+i);
}
avg=(float)sum/numOfStudents;
if(numOfStudents%2==0)
{
left=*(arr+(numOfStudents/2)); //When number of Students is even
right=*(arr+((numOfStudents/2)-1));
median=(left+right)/2;
}
else
median=*(arr+(numOfStudents/2)); //When number of students is odd
map<int,int>::iterator it=m.begin();
int maxmFrequency=0;
while(it!=m.end())
{
if(it->second>maxmFrequency) //Iterating over map to get the highest frequency
maxmFrequency=it->second;
it++;
}
cout<<"Average : "<<avg<<endl;
cout<<"Median : "<<median<<endl;
if(maxmFrequency==1)
cout<<"Frequency of each element is 1 hence Mode cannot be found"<<endl;
else
{
it=m.begin();
cout<<"Mode : ";
while(it!=m.end())
{
if(it->second==maxmFrequency)
cout<<it->first<<" "; //When more than one element has maximum frequency then we have to print all the elements as mode
it++;
}
cout<<endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.