Programming in C

(Barry) #1
A Structure for Storing the Date 167

Program 9.1 Illustrating a Structure
// Program to illustrate a structure

#include <stdio.h>

int main (void)
{
struct date
{
int month;
int day;
int year;
};

struct date today;

today.month = 9;
today.day = 25;
today.year = 2004;

printf ("Today's date is %i/%i/%.2i.\n", today.month, today.day,
today.year % 100);

return 0;
}

Program 9.1 Output
Today's date is 9/25/04.

The first statement inside maindefines the structure called dateto consist of three inte-
ger members called month,day,and year. In the second statement, the variable todayis
declared to be of type struct date.The first statement simply defines what a date
structure looks like to the C compiler and causes no storage to be reserved inside the
computer.The second statement declares a variable to be of type struct dateand,
therefore,doescause memory to be reserved for storing the three integer values of the
variable today. Be certain you understand the difference between defining a structure
and declaring variables of the particular structure type.
After todayhas been declared, the program then proceeds to assign values to each of
the three members of today, as depicted in Figure 9.1.

TEAM FLY

Free download pdf