08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 ■ Arrays

This sets elements score[0], score[1], score[2], up to score[19] to 0. Elements score[20]

to score[59] remain undefined.

C provides another way of initializing an array – in its declaration. Consider this:

int score[5] = {75, 43, 81, 52, 68};

This declares score to be an array of size 5 and sets score[0] to 75, score[1] to 43, score[2]

to 81, score[3] to 52 and score[4] to 68.

The initial values are enclosed in braces and separated by commas. No comma is necessary

after the last value, but it is not an error to put one.

If fewer than5 values are supplied, then 0s would be used to fill out the array. For example,

the declaration

int score[5] = {75, 43};

sets score[0] to 75, score[1] to 43, score[2] to 0, score[3] to 0 and score[4] to 0.

If more than 5 values are supplied, you would get a warning or an error, depending on

your compiler setting. For example, the following will generate a warning or error since there are

8 values:

int score[5] = {75, 43, 81, 52, 68, 49, 66, 37};

It is possible to omit the size of the array and write, for example, this:

int score[] = {75, 43, 81, 52, 68, 49, 66, 37};

In this case, the compiler counts the number of values to determine the size of the array.

Here, the number of values is 8, so it is the same as if we had written this declaration:

int score[8] = {75, 43, 81, 52, 68, 49, 66, 37};

As another example, suppose we wanted to store the number of days in a month in a leap

year. We could use this:

int month[] = {31,29,31,30,31,30,31,31,30,31,30,31};

This would set month[0] to 31, month[2] to 29, etc., and we would have to remember that

month[0] refers to January, month[1] refers to February, and so on. We can get around this by

using the following:

int month[] = {0,31,29,31,30,31,30,31,31,30,31,30,31};

Now, month[1] is 31and refers to January, month[2] is 29, and refers to February, and so on—this

is more natural than the previous declaration. The element month[0] is 0 but we ignore it (see next).

202

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!