20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

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

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

188 Chapter 9 Work<strong>in</strong>g with Structures<br />

Or, you can <strong>in</strong>itialize this variable to the same values with the follow<strong>in</strong>g statement:<br />

struct month aMonth = { 31, { 'J', 'a', 'n' } };<br />

To go one step further, you can set up 12 month structures <strong>in</strong>side an array to represent<br />

each month of the year:<br />

struct month months[12];<br />

Program 9.7 illustrates the months array. Its purpose is simply to set up the <strong>in</strong>itial values<br />

<strong>in</strong>side the array and then display these values at the term<strong>in</strong>al.<br />

It might be easier for you to conceptualize the notation that is used to reference particular<br />

elements of the months array as def<strong>in</strong>ed <strong>in</strong> the program by exam<strong>in</strong><strong>in</strong>g Figure 9.3.<br />

Program 9.7<br />

Illustrat<strong>in</strong>g Structures and Arrays<br />

// Program to illustrate structures and arrays<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

<strong>in</strong>t i;<br />

struct month<br />

{<br />

<strong>in</strong>t numberOfDays;<br />

char name[3];<br />

};<br />

const struct month months[12] =<br />

{ { 31, {'J', 'a', 'n'} }, { 28, {'F', 'e', 'b'} },<br />

{ 31, {'M', 'a', 'r'} }, { 30, {'A', 'p', 'r'} },<br />

{ 31, {'M', 'a', 'y'} }, { 30, {'J', 'u', 'n'} },<br />

{ 31, {'J', 'u', 'l'} }, { 31, {'A', 'u', 'g'} },<br />

{ 30, {'S', 'e', 'p'} }, { 31, {'O', 'c', 't'} },<br />

{ 30, {'N', 'o', 'v'} }, { 31, {'D', 'e', 'c'} } };<br />

pr<strong>in</strong>tf ("Month<br />

pr<strong>in</strong>tf ("-----<br />

Number of Days\n");<br />

--------------\n");<br />

for ( i = 0; i < 12; ++i )<br />

pr<strong>in</strong>tf (" %c%c%c<br />

%i\n",<br />

months[i].name[0], months[i].name[1],<br />

months[i].name[2], months[i].numberOfDays);<br />

}<br />

return 0;

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

Saved successfully!

Ooh no, something went wrong!