Help with C please, and many thanks Write a program to find the number of elemen
ID: 3864917 • Letter: H
Question
Help with C please, and many thanks
Write a program to find the number of elements above the average value in file. Load the file to an array, compute average using the array and find the number elements above average using the array. Use dynamic memory allocation using to allocate the array and if the allocated size is not enough, use real loc to double size of the array. Start with an array of size 10. Make sure you free the memory allocated before you end the program. You can implement the following functions your program. double average (double *ptr, int size) int above average (double *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. 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 freed Submit your program electronically using the blackboard systemExplanation / Answer
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *ptr_file;
char buf[1000];
int *ptr;
int ctr = 1;
int k;
int sum = 0;
int initalisizeofthearray = 10;
int currentMaxSizeofTheArray = 10;
int noOfElements = 0;
int z;
float avg;
ptr = (int*) calloc(initalisizeofthearray, sizeof(int));
printf("Allocated %d integers ",initalisizeofthearray);
ptr_file =fopen("input.txt","r");
if (!ptr_file)
return 1;
while (fgets(buf,1000, ptr_file)!=NULL){
if (ctr == currentMaxSizeofTheArray){
realloc(ptr, initalisizeofthearray*2);
currentMaxSizeofTheArray = initalisizeofthearray*2;
printf("Reallocated %d integers ",currentMaxSizeofTheArray);
}
*(ptr + ctr - 1) = atoi(buf);
ctr++;
}
for ( k = 0;k < ctr ; k++){
sum = sum + *(ptr+k);
}
avg = sum / ctr;
for (z = 0;z<ctr;z++){
if(*(ptr+z) >avg){
noOfElements++;
}
}
printf("%d elements in the array are above average %f",noOfElements,avg);
free(ptr);
printf("Dynamic array freed");
fclose(ptr_file);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.