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. Bear with me in this long code.So ,I wrote the code for this and I ran it and it works.Here's the code.I want to know is there any other way to do this in a shorter or simpler way?
#include <stdio.h>
#include <stdlib.h>
#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<n; i++) {
printf("Please enter #%d: ", i+1);
scanf("%d", arr + i); /* or &arr[i] */
}
}
double findAverage(int arr[], int n) {
int sum = 0;
int i;
for(i=0; i<n; i++)
sum+=arr[i];
return (double)sum / n;
}
int countAboveAverage(int arr[], int n, double average) {
int count=0;
int i;
for(i=0; i<n; i++)
count = arr[i] > average ? count+1: count;
return count;
}
printf("The number of elements above the average is %d:");
– Loki Astari May 2 '13 at 11:36