Now suppose that you want to fill an array using data in a file. You probably do not know exactly how many objects you need to store. Accordingly, you need an approach to dealing with uncertainty.
One approach, about which you learn in the hardcopy version of this book, is to limit
wasted memory by allocating memory for objects at run time. In this
chapter, you learn about a simpler approach: You define an object array
that is sure to be large enough to hold all the objects you can possibly
encounter. Then, you proceed to fill that array using a while
reading or for
reading pattern.
In the following program, for example, you create two arrays, each of which
can hold up to 100 integers representing the prices per share and the
numbers of shares involved in a group of trades. Then, you fill part or all
of that array with floating-point numbers and integers using a for
reading pattern in which the value of the limit
variable is counted
up to the total number of pricenumber pairs. Finally, you use another
for
loop to add up the products of the numbers:
#include/* Define trade_price */ double trade_price (double p, int n) { return p * n; } /* Define global arrays */ double price[100]; int number[100]; main ( ) { /* Declare various variables */ int limit, counter; double sum = 0.0; /* Read numbers and stuff them into arrays */ for (limit = 0; 2 == scanf ("%lf%i", &price[limit], &number[limit]); ++limit) ; /* Add all products of corresponding elements in the two arrays */ for (counter = 0; counter < limit; ++counter) sum = sum + trade_price (price[counter], number[counter]); /* Display sum */ printf ("The total value of the %i trades is %f.\n", limit, sum); } --- Data --- 10.2 600 12.0 100 13.2 200 --- Result --- The total value of the 3 trades is 9960.000000.