Note: there are similar techniques shown in the linear equation solver that was lightly discussed earlier.
Write a program to average a set of integers. Implement the program by reading the data into an array (at most 100 items), echoing them 3 items per line, and printing the average.
get the data into an array, (keeping the count of data entered) find the average of the data print the data, 3 items per line print the averageWe will implement these steps as function calls. (Note, we define a macro for the maximum size of the array).
int get_data(int *d, int sz);
float avg_data( int nums[], int how_many);
void print_data( int data[], int s);
#define SIZE 100 #define DATA_PER_LINE 3 main() { int data[SIZE]; /* the data array */ int count; /* the number of data items in the array */ float average; /* the average value */ /* get the data into an array, keeping the count of data entered */ count = get_data(data,SIZE); /* find the average of the data */ average = avg_data(data, count); /* print the data, 3 items per line */ print_data(data, count); /* print the average */ printf("\nthe average is %f\n",average); } int get_data(int *d, int sz) { int i = 0; while(scanf("%d", d[i]) != EOF) i++; return i; } float avg_data( int nums[], int how_many) { int i; int sum = 0; for( i = 0; i < how_many; i++) sum += nums[i]; return (float) sum / how_many; } void print_data( int data[], int s) { int i; for(i = 0; i < s; i++) { if(i % DATA_PER_LINE == 0) putchar('\n'); printf("%d ", data[i]); } putchar('\n'); }