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

In our example, each element of the array is an int and can be used in any way that an

ordinary int variable can. In particular, a value can be stored in it, its value can be printed, and it

can be compared with another int.

We could picture score as in Figure 8-1.

Figure 8-1. Declaration of int score[60]

Like a simple variable, when an array is declared, the values of its elements remain undefined

until we execute statements that store values in them. This is discussed in Section 8.3, next.

To give another example, suppose we need to store the item numbers (integers) and prices

(floating-point numbers) of 100 items. We can use one array (item, say) to hold the item numbers

and another array (price, say) to hold the prices. These can be declared with this:

int item[100];

double price[100];

The elements of item range from item[0] to item[99] and the elements of price range from

price[0] to price[99]. When we store values in these arrays (see next), we will ensure that

price[0] holds the price of item[0];

price[1] holds the price of item[1];

and, in general,

price[i] holds the price of item[i].

8.3 Store Values in an Array

Consider the array score. If we wish, we could set selected elements to specific values, as follows:

score[3] = 56;

score[7] = 81;

199

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!