Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program that calculates statistics on a set of test scores. The scor

ID: 3664537 • Letter: W

Question

Write a C++ program that calculates statistics on a set of test scores. The scores should be stored in a dynamically allocated array.

The Program should go with the following logic:

+Ask the user for the file name.

+Open a file that has a set of test scores. The first value is the number of scores in the file.

+Allocate an array to hold the scores. Only dynamic allocation will be accepted.

+Read the test scores into the array. Have a separate function to open the file and read the scores.

+Sort the scores in ascending order using qsort()

+Print the sorted scores. Have a separate function to print the scores.

+Calculate and print the average and the median and mode of the scores. Have separate functions to calculate average, median and mode.

+Release the memory that you allocated and close the file.

Here's the score.txt file:
30
90 87 92.5 68 91 74 73.5 88.5 89 97 100 61.5 74 85 87 73 92.5 99 87 92 66 77 79 80.5 87 80 94.5 61 71 72

Explanation / Answer

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

int floatcomp(const void* elem1, const void* elem2)
{
if(*(const float*)elem1 < *(const float*)elem2)
return -1;
return *(const float*)elem1 > *(const float*)elem2;
}
void printarray(float * ptr,int size){
int i;
printf(" Sorted array is: ");
for(i=0;i<size;i++)
printf("%.1f ",ptr[i]);

}
void printavg(float * ptr,int size){
int i;
float avg=0;
for(i=0;i<size;i++)
avg = avg + ptr[i];
avg = avg /size;
printf(" Average = %f",avg);

}
void printmedian(float * ptr,int size){
int i;
float median;
if(size % 2 == 0 )
printf(" Median is: %f",(ptr[size/2 -1]+ptr[size/2])/2);
else
printf(" Median is: %f",ptr[size/2] );
}

void printmode(float *ptr,int size){
int flag = 1,i;
float flag_value = ptr[0];
int cur_flag = 1;
for(i=1;i<size;i++){
cur_flag =1;
while(ptr[i]==ptr[i-1] ){
cur_flag++;
i++;
}
if(cur_flag > flag){
flag = cur_flag;
flag_value = ptr[i-1];
}
}
printf(" Mode is: %f",flag_value );
}

void fileread(char* S){
char ch;
FILE *fp;
fp = fopen(S,"r");
if( fp == NULL ){
printf("Error while opening the file. ");
exit(0);
}
int n ;
fscanf(fp,"%d",&n);
printf("Size of the data %d items ",n);
float *ptr=(float*)malloc(n*sizeof(float)); /*memory allocated using malloc*/
if(ptr==NULL){
printf("Error! memory not allocated.");
exit(0);
}
int i;
for(i=0;i<n;i++)
fscanf(fp,"%f",&ptr[i]);
fclose(fp);
qsort(ptr, n, sizeof(float), floatcomp);
printarray(ptr,n);
printavg(ptr,n);
printmedian(ptr,n);
printmode(ptr,n);
free(ptr);
}
int main(){
char S[50];
printf("Enter the file name");
gets(S);
fileread(S);
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote