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

Figure 8-2. The array day

If d contains a value from 1 to 7, then day[d] contains the name of the day corresponding to

d. For instance, if d is 3, day[d] contains Tuesday. But how can we store the names of the days in

an array? What kind of array would we need?

We will need an array where each element can hold a string – an array of strings. But a string

itself is stored in an array of characters. So we need an array of “array of characters” – we need a

two-dimensional array. Consider the declaration

char day[8][10];

We can think of day as having 8 rows and 10 columns. If we store the name of a day in each

row, then we can store 8 names. Each name is stored in an array of 10 characters. The rows are

numbered from 0 to 7 and the columns are numbered from 0 to 9. As hinted in the above diagram,

we will not use row 0. We will store the names in rows 1 to 7. If we store the names of the days in

this array, it will look like this (we put the null string "" in day[0]):

C lets us to refer to the ith row with day[i]. If we need to, we can use day[i][k] to refer to

the character in row i and column k. For example, day[3][2] is e and day[7][4] is r.

We can declare the array day and initialize it with the names of the days using this:

char day[8][10] = {"", "Sunday", "Monday", "Tuesday",

"Wednesday", "Thursday", "Friday", "Saturday"};

This declaration will create the array shown in Figure 8-3. The strings to be placed in the array

are enclosed by { and } and separated by commas with no comma after the last one. The first

string, the null string, is placed in day[0], the second in day[1], the third in day[2], and so on.

226

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!