Computer Science Programming in C. Read the values and store them into an array
ID: 3569604 • Letter: C
Question
Computer Science Programming in C. Read the values and store them into an array of float or double values. Be sure to count how many numbers are actually read into the array and return the count to main. The rest of your functions should use this count to process the array's contents. This is known as a partially filled array and is discussed starting on page 399 In your text. Input Validation: Do not accept negative numbers or numbers greater than 100 for exam scores. Your program should discern any out of bounds values in the data file. Calculate the following and write the results into a file named rosults.txt: Glass average highest score lowest score most frequent score (mode for data set). Assume that the scores range from 0 to 100. Median of the scores in the data set. To find this, sort the array in ascending order. Use the bubble sort algorithm to sort the array, then find the middle value or the average of the 2 middle values if the number of scores is even. Write the sorted array into the results .txt data file too.Explanation / Answer
#include<stdio.h>
int readValues(double arr[]){
FILE *ptr;
double num;
int i=0;
ptr = fopen("exam.txt", "r");
while(fscanf(ptr, "%lf", &num) > 0){
if(num > 0 && num <=100){
arr[i] = num;
i++;
}
num = getc(ptr);
}
fclose(ptr);
return i;
}
void calculateAndWrite(double arr[], int count){
double sum = arr[0];
double high = arr[0];
double low = arr[0];
int freqArr[100] = {0};
double modeScore = 0;
int modeFreq = 0;
int i,j;
double temp, median;
FILE *ptr;
for(i =1; i<count; i++){
sum += arr[i];
if(arr[i] > high){
high = arr[i];
}
if(arr[i] < low){
low = arr[i];
}
freqArr[(int)arr[i]]++;
if(freqArr[(int)arr[i]] > modeFreq ){
modeFreq = freqArr[(int)arr[i]];
modeScore = arr[i];
}
}
for(i=0 ; i < count; i++){
for(j = 0; j <count; j++){
if(arr[i] < arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
if(count%2 == 0){
median = (arr[count/2] + arr[(count/2) + 1])/2;
}else{
median = arr[(count/2) + 1];
}
ptr = fopen("results.txt","w");
fprintf(ptr, "Class Average = %lf ", sum/count);
fprintf(ptr, "Highest Score = %lf ", high);
fprintf(ptr, "Lowest Score = %lf ", low);
fprintf(ptr, "Most Frequent Score = %lf ", modeScore);
fprintf(ptr, "Median of the Score = %lf ", median);
fprintf(ptr, "Sorted Scores are as follow : ", high);
for(i = 0; i< count ; i++){
fprintf(ptr, "%lf ", arr[i]);
}
fclose(ptr);
}
int main(){
double arr[50] = {0};
int count;
count = readValues(arr);
calculateAndWrite(arr, count);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.