08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8 ■ Arrays

But what if we wish to set the 60 locations to 60 scores? Would we have to write 60 statements

as in the following?

score[0] = 45;

score[1] = 63;

score[2] = 39;

.

.

score[59] = 78;

This is certainly one way of doing the job, but it is very tedious, timeconsuming, and

inflexible. A neater way is to let the subscript be a variable rather than a constant. For example,

score[h] can be used to refer to the score in location h; which score is meant depends on the

value of h. If the value of h is 47, then score[h] refers to score[47], the score in location 47.

Note that score[h] can be used to refer to another score simply by changing the value of h,

but, at any one time, score[h] refers to one specific score, determined by the current value of h.

Suppose the 60 scores are stored in a file scores.txt. The following code will read the 60

scores and store them in the array score:

FILE * in = fopen("scores.txt", "r");

for (int h = 0; h < 60; h++)

fscanf(in, "%d", &score[h]);

Suppose the file scores.txt begins with the following data:

45 63 39 ...

The for loop is executed with the value of h ranging from 0 to 59:

• When h is 0, the first score, 45, is read and stored in score[0];

• When h is 1, the second score, 63, is read and stored in score[1];

• When h is 2, the third score, 39, is read and stored in score[2];

and so on, up to

• When h is 59, the 60th score is read and stored in score[59].

Note that this method is much more concise than writing 60 assignment statements. We are

using one statement

fscanf(in, "%d", &score[h]);

to store the scores in 60 different locations. This is achieved by varying the value of the subscript, h.

This method is also more flexible. If we had to deal with 200 scores, say, we only need to change

60 to 200 in the declaration of score and in the for statement (and supply the 200 scores in the

data file). The previous method would require us to write 200 assignment statements.

200

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!