patterncMinor
Displaying the number of elements larger than the average of an array
Viewed 0 times
numberthelargerelementsarraythanaveragedisplaying
Problem
I have to write a program in C that reads an array with n elements and then displays how many elements are bigger than the average of the elements of the vector.
Is there any other way to do this in a shorter or simpler way?
Is there any other way to do this in a shorter or simpler way?
#include
#include
#define SIZE 100
void readArray(int [] , int );
double findAverage(int [] , int);
int countAboveAverage(int [] , int , double);
int main(int argc, char* argv []) {
//declare an array of size 100
int arr[SIZE];
int n;
printf("Enter a value for n: ");
scanf("%d", &n);
if(n==0) {
fprintf(stderr, "Your size of n is too big. Run the program again.\n");
exit(1);
}
//this function will do the reading
readArray(arr, n);
//this is a function to find the average
double average = findAverage(arr, n);
//this is a function that will count the number above average
int count = countAboveAverage(arr, n, average);
printf("The number of elements above the average is %d:");
return EXIT_SUCCESS;
}
void readArray(int arr[], int n) {
int i;
for(i=0; i average ? count+1: count;
return count;
}Solution
A few extra comments:
the error printf says
-
define loop variables in the loop and always use braces, even when not necessary:
-
-
personally I'd avoid using unsigned types (suggested by @Sulthan) as it often
leads to unexpected arithmetic results. If you do use it, make sure you
enable the necessary compiler warnings.
- define
mainat the bottom so that prototypes are unnecessary
- define local functions 'static'
- if you are going to use EXIT_SUCCESS then also use EXIT_FAILURE
- your comments are just noise (no useful information) and should be deleted
- add a
\nat the end of the finalprintf(which is missingcount)
- you don't check for
nbeing greater thanSIZE, only for zero (although
the error printf says
n is too big)-
define loop variables in the loop and always use braces, even when not necessary:
for (int i=0; i<n; ++i) {
// do something
}-
findAverage and countAboveAverage should declare arr as conststatic double findAverage(const int arr[], int n);-
personally I'd avoid using unsigned types (suggested by @Sulthan) as it often
leads to unexpected arithmetic results. If you do use it, make sure you
enable the necessary compiler warnings.
Code Snippets
for (int i=0; i<n; ++i) {
// do something
}static double findAverage(const int arr[], int n);Context
StackExchange Code Review Q#25725, answer score: 4
Revisions (0)
No revisions yet.