Moreover once we decide on a size and declare the array the size cannot be

# Moreover once we decide on a size and declare the

This preview shows page 20 - 21 out of 21 pages.

Moreover, once we decide on a size and declare the array, the size cannot be changed – array is fixed size data structure. There are many programming situations where we do not really know the number of elements before hand. For example, suppose we wish to read scores of students from a data file, store them into an array and then scan through the array to find the average. Obviously, we do not know how many scores are in the file. So what should be the array size? One solution is to declare the array big enough so that it can work in the worst-case scenario. For the scores data file, we can safely assume that no section is more than 50 students. However, in this case, the array will be partially empty and we cannot use SIZE in processing it. We must keep track of the actual elements in the array using another variable. 21 Example 11 /* Finds the average score by reading scores from a data file */ #include <stdio.h> #define SIZE 50 double get_average(double a[], int size); int main(void) { double x[SIZE], score, average; int status, count=0 ; FILE *infile; infile = fopen("scores.txt", "r"); status = fscanf(infile, "%lf", &score); while (status != EOF) { x[count] = score; count++; status = fscanf(infile, "%lf", &score); } fclose(infile); average = get_average(x, count ); printf("The average of the scores in the file is %.2f\n", average); system("pause"); return 0; } double get_average(double a[], int size) { int i; double sum = 0; for (i = 0; i < size; ++i) sum += a[i]; return sum/size; } #### You've reached the end of your free preview.

Want to read all 21 pages?

• Spring '10
• baleh
• Array, size
• • •  