*program is in c* Write a program to find the number of elements above the avera
ID: 3831665 • Letter: #
Question
*program is in c*
Write a program to find the number of elements above the average value in a file. Load the file to an array, compute average using the array and find the number of elements above average using the array. Use dynamic memory allocation using calloc to allocate the array and if the allocated size is not enough, use realloc to double the size of the array. Start with an array of size 10. Make sure you free the memory you allocated before you end the program. You can implement the following functions in your program. double average(int *ptr, int size) int aboveaverage(int *ptr, int size, double average) Sample execution is given below. Print a message on the screen when you allocate, reallocate and free the memory as shown below. Use argc. argv and file operations for this recitation. fox01> recitation8 a.txt Allocated 10 integers Reallocated to 20 integers Reallocated to 40 integers Reallocated to 80 integers Reallocated to 160 integers 47 elements are above average of 477.455446 Dynamic array freedExplanation / Answer
Please find my code.
#include <stdio.h>
#include <stdlib.h>
double average(double *ptr, int size);
int aboveaverage(double *ptr, int size, double average);
int main(){
// opening file
FILE* myfile=NULL;
myfile=fopen("a.txt","r");
if (myfile == NULL)
{
printf("Could not open file ");
return 0;
}
// allocationg 10 elements
int size = 0;
int capacity = 10;
double *arr = calloc(10, sizeof(double));
printf("Allocated 10 integers ");
double num;
while (fscanf(myfile, "%lf", &num) == 1) {
if(size == capacity){
capacity = capacity + 10;
arr = (double *)realloc(arr, sizeof(double)*capacity);
printf("Reallocated to %d integers ", capacity);
}
arr[size] = num;
size++;
}
double avg = average(arr, size);
int count = aboveaverage(arr, size, avg);
printf("%d elements are above average of %lf ", count, avg);
fclose(myfile);
// deleting the memory
free(arr);
printf("Dynamica array freed ");
return 0;
}
// function definations
double average(double *ptr, int size){
double sum = 0;
int i;
for(i=0; i<size; i++)
sum = sum + ptr[i];
return sum/size;
}
int aboveaverage(double *ptr, int size, double average){
int count = 0, i;
for(i=0; i<size; i++){
if(ptr[i] > average)
count++;
}
return count;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.