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

If we wish to print the scores as they are read, we could write the for loop like this:

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

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

printf("%d\n", score[h]);

}

On the other hand, if we wish to print the scores after they are read and stored in the array,

we could write another for loop:

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

printf("%d\n", score[h]);

We have used the same loop variable h that was used to read the scores. But it is not

required that we do so. Any other loop variable would have the same effect. For instance, we

could have written:

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

printf("%d\n", score[x]);

What is important is the value of the subscript, not the variable that is used as the subscript.

We often need to set all elements of a numeric array to 0. This may be necessary, for instance,

if we are going to use them to hold totals, or as counters. For example, to set the 60 elements of

score to 0, we could write:

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

score[h] = 0;

The for loop is executed 60 times, with h taking on the values 0 to 59:

• The first time through the loop, h is 0, so score[0] is set to 0.

• The second time through the loop, h is 1, so score[1] is set to 0.

and so on, until

• The 60th time through the loop, h is 59, so score[59] is set to 0.

If we want to set the elements to a different value (-1, say), we could write:

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

score[h] = -1;

It should be noted that even though we have declared score to be of size 60, it is not required

that we use all the elements. For example, suppose we want to set just the first 20 elements of

score to 0, we could do this with the following:

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

score[h] = 0;

201

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!