CHAPTER 10

Structures

Structures are one of the very important features available in C. These are chiefly used to build various types of data structures that are generally used in the domain of computers. In this chapter the meaning of structures, defining a structure, declaring structure variables and using structure variables are discussed with the aid of some simple examples.

Things that exist around us in reality are called entities. These entities are identified by a name and will have a number of properties associated with each of them. A book, a student, a car, a date are all some examples of entities. Some of the properties or attributes associated with each one of these named entities are given in the following table.

imagesimages

The relationship between the entities and their attributes can be diagrammatically represented as shown below. Such diagrams are generally called entity relationship diagrams (ER-Diagrams).

images

Processing of these entities or objects using computers need the entities and their attributes to be written in some compact form having certain definite pattern. For example, the entities student and book can be represented in a compact form as shown below.

STUDENT ( usn, name, branch of study, date of birth )

BOOK ( isbn, title, author, price )

It may be observed that an entity representation, as given above, describes its physical layout or format. These physical layouts or formats of entities with which all the attributes are put together under a common name are referred to by different terminologies in different computer languages. For example, they are called records in COBOL, objects (of course, along with some procedures attached to them) in C++, structures in C and so on.

Thus, in C, a structure is defined as the compact form representation of an entity along with all or some of its attributes. For example, the structure of the entity book may be defined as shown in the following figure.

images

Obviously, the name of the above structure is book. Often, name of a structure like book is also referred to as the structure tag or simply tag. As shown in the above figure, all the attributes are listed inside a pair of curly braces immediately after the structure name or the structure tag. Every attribute is represented as a variable name of some suitable data type and size. These variable names of the attributes inside the curly braces of structure are called the members or the elements of a structure. The use of the C keyword struct in the beginning and a semicolon (;) at the end of a structure definition are compulsory. The use of structure tag is optional.

A structure may, however, also be defined using the C keyword typedef as shown below

images

The structure definition as above creates a new data type called BOOK. For the sake of convenience, generally the new data types created using the typedef facility are written using only uppercase alphabets.

Structures are like arrays in that they both group a number of individual elements into a single larger unit. But while a structure usually groups items of different types, an array groups items of the same type. More importantly, the members of a structure are accessed by their name (as will be explained very shortly) while the elements of an array are accessed by an index number, i.e. the subscript. Another important point to be noted here is that like arrays, structures are also transmitted or passed-on between different functions by their starting addresses, i.e. by using the call-by-implication technique. It is interesting to note that we can have arrays of structures (i.e. arrays whose elements are structures, as in Section 10.4) and structures with arrays as its members.

Before using the variables of the structure type (i.e. structure variables), structures must be defined. A structure definition may appear either in the beginning of a function in which it is used or in the beginning of a program immediately after the pre-processor directives, just like global variables.

A mere structure definition describes just a template, i.e. the shape of the structure. It will not allocate any memory area. Memory area will be allocated only when structure type variables are declared.

The required structure variables are declared either using or without using the name or tag of the structure definition. Let book1 and book2 be two required structure variables. These two structure variables can be declared in any of the following ways.

images

In A and B forms the required structure variables have been declared along with the structure definition itself. In the C and D forms the required variables have been declared at a later stage, independently of the structure definition.

It may be observed that in the A form there is no structure name or tag. The disadvantage with this method is that, one cannot have structure variables declared as and when they are required. If required, the shape of the structure, i.e. the structure has to be defined once again. The B form is alright. However, it is customary to declare the required structure variables independently along with other type of variables as shown in form C. It may be noted that these independent declarations need the struct key word to be used during all declarations.

The D form uses the key word typedef in its definition. As shown in form D any new data type (like BOOK) may be defined. This new data type, i.e. BOOK is used to declare the required structure variables like book1, book2, etc. Here it may be noticed that it is not necessary to use the key word struct during structure variable declarations and hence is comfortable to use. The reader is advised to practice using either of the forms given in C or D depending up on his/ her convenience. In fact, if necessary, even form D can have a tag.

After defining a structure and declaring structure variables, the structure variables are used just like all other types of variables. As in the case of arrays, with structures also the manipulations are done at individual elements level. It may be noted that an individual element in the case of a structure is its individual member. In other words, names of the structure members are used in computations. As it is known (discussed in Chapter 6) individual array elements are accessed using index numbers or subscripts. Individual members of a structure are accessed using an operator called the dot (.) operator or the period operator. This dot operator (.) along with the structure variable name and the member name is used to access any required individual element as shown in the following figure.

For example, the ‘title’ of book1 is accessed by first accessing the required structure variable name [i.e. book1] and then accessing the required member [i.e. title]. Thus the title of the type book, book1 is accessed using an expression of the form book1.title.

images

Accessing the member of a structure variable

It should be noted that the dot (.) operator is an unary operator and has the highest precedence among all operators. The dot expressions are evaluated from left to right.

10.1 DEFINING A STRUCTURE, DECLARING, STRUCTURE VARIABLES, ASSIGNING VALUES TO STRUCTURE MEMBERS AND PRINTING OUT STRUCTURE MEMBER VALUES

The Method

In this example, a structure called student is defined. This structure is assumed to have four members or elements. Let these four members be university seat number (usn), name, date-of-birth and marks. Before actually defining a structure, it is necessary to decide about the size and/or type of the values that are expected to be stored in its member variable names. Let the size of the usn be 10 characters, size of the name be 20 characters, date-of-birth be 10 characters and marks be of integer type. The required structure may be defined either within the main( ) or before the main( ). In this example the structure has been defined within the main( ).

A structure variable student1 is declared in the beginning of the main( ), immediately after the structure definition. Values to the different members of structure variables may be either initialized directly or assigned by inputting the values using scanf( ) and/or gets( ) functions, as in the case of other types of variables. In this example the necessary values to the structure members have been assigned interactively using the above mentioned functions.

The values assigned to the different members of the structure student1 are displayed or printed out by first accessing each member using the dot (.) operator and then using the printf( ) function.

C-Tips

In this example, the keyword struct has been used both to define a structure as well as to declare a structure variable. Values to the char type of members of the structure are input using gets( ) function. Values to the int type of members are input using scanf( ) function. Values of the different members of the structure are output using the printf( ) statement. The mechanism used to access the different members of the structure is similar to the one shown in the previous page.

The Program

/* Defining a structure, declaring a structure variable, reading and
printing its members */

#include<stdio.h>
#include<conio.h>
main()
{
   struct student                /* Defining the structure */
   {
      char name[20];
      char usn[10];
      char birth_date[20];
      int marks;
   };

   struct student student 1;     /* Declaring a structure variable */

   clrscr();

   /* Accepting the student details */
   printf(“
		Enter the student name : ”);
   gets(student1.name);
   printf(“%s”,student1.name);

   printf(“
		Enter the University Seat Number: ”) ;
   gets(student1.usn);
   printf(“%s”,student1.usn);

   printf (“
		Enter the Date of Birth : ”) ;
   gets(student1.birth_date);
   printf(“%s”,student1.birth_date);

   printf(“
		Enter the marks: ”) ;
   scanf(“%d”,&student1.marks);
   printf(“%d”,student1.marks);

   /* Printing the student details */
   printf(“
		__________________”);
   printf(“
		Student's Details :
”);
   printf(“		__________________
”);
   printf(“
		Name                      : %s”, student1.name);
   printf (“
		University Seat Number   : %s”, student1.usn);
   printf(“
		Date of Birth             : %s”, student1.birth_date);
   printf(“
		Marks                     : %d”, student1.marks);

}

10.2 ARRAY OF STRUCTURE VARIABLES: LISTING NAMES OF STUDENTS WHO HAVE SCORED MORE THAN 60% OF TOTAL MARKS IN THREE SUBJECTS USING STRUCTURE VARIABLES

The Method

A student structure having the university seat number (usn), name, sub1, sub2, sub3, total and percent as its members is first defined. Marks scored in individual subjects are stored in sub1, sub2 and sub3. As we have to consider many number of students, a group of structures has to be used. Obviously, this group of structures will be nothing but an array of structure variables of the type student structure. In this example, the required structure has been defined before the main( ) using the typedef mechanism. An array of structures (say, s[ ]) is declared along with other local variables, as usual, inside the main( ).

The values for the different members of all the structure variables are input interactively using the scanf( ) and gets( ) functions. As usual, the input values are output as and when they are input.

In order to determine the total marks and the percentage of marks, all the subject fields of a structure variable s[i] are accessed using dot (.) operator expressions of the form

images

The mechanism of accessing a structure member of a structure variable within an array is shown in the figure on page 252. Obviously, the above mentioned type of statements are repeatedly executed and the required result is printed out under the control of a for loop control structure.

C-Tips

In this example, the student structure has been defined before the main( ). Individual elements of an array, of whatever the type of elements it is made up of, are accessed by using one or more subscripts. Since we are dealing with an one-dimensional student array use of only one subscript in this example is sufficient. As such the subscript i has been used to access individual structure variables in the array s[]. The individual member of a specific structure variable, say total, is accessed using the dot (.) operator by writing an expression of the form s[i].total.

images

Accessing the member of a structure variable within an array of structures.

Flowchart

images

The Program

/* Program to list the names of students who have scored more than 60%
of total marks in three subjects using structure variables */

#include<stdio.h>
#include<conio.h>

struct student                     /* Defining the structure */
{
   char name[30];
   char usn[10];
   int sub1;
   int sub2;
   int sub3;
   int total;
   float percent;
};

main()
{
   int i,n;
   struct student s[20];    /* Declaring an array of structures */

   clrscr();
   printf(“		Enter the number of students: ”) ;
   scanf(“%d”,&n);
   printf(“%d”,n);

   for(i=0;i<n;++i)
   {
     getchar();           /* to accept the newline character */

     /* Accepting the students details */
     printf(“

		Enter the student name : ”) ;
     gets(s[i].name);
     puts(s[i].name);

     printf(“
		Enter the student University Seat Number: ”) ;
     gets(s[i].usn);
     puts(s[i].usn);

     printf(“
		Enter the marks of subject1: ”) ;
     scanf(“%d”,&s[i].sub1);
     printf(“%d”,s[i].sub1);
     printf(“
		Enter the marks of subject2: ”) ;
     scanf(“%d”,&s[i].sub2);
     printf(“%d”,s[i].sub2);
     printf(“
		Enter the marks of subject3: ”) ;
     scanf(“%d”,&s[i].sub3);
     printf(“%d”,s[i].sub3);
   }
     /* printing the students name,USN and percentage who have secured more than 60% */
     printf(“

		List of students Name , University Seat Number and Percentage
		who have scored more than 60% marks
”);
     printf(“
		_____________________”);
     printf(“
		Name			Rollnumber	Percentage
”);
     printf(“		______________________
”);
     for(i=0;i<n;++i)
     {
       /* calculating the total and percentage */
       s[i].total = s[i].sub1+s[i].sub2 + s[i].sub3;
       s[i],percent= s[i].total / 3.0;

       if(s[i].percent>=60)
         printf(“		%-20s	%s		%.2f
”,s[i].name ,s[i].usn,s[i].percent);
     }

}

10.3 SUM OF TWO COMPLEX NUMBERS-PASSING STRUCTURE VARIABLE TO FUNCTION

A complex number will be of the form ( x ± i y) where x is called the real part and y is called the imaginary part. These real and imaginary parts could be either integers or floats. In mathematics, complex numbers are just another type of numbers like integers, reals etc. However, in many computer languages including C there is no fundamental data type available to handle these types of numbers directly. One of the methods generally employed to handle complex numbers in C is to use structures. The shape of the structure of a complex number will be as follows:

typedef struct
{
    float part_real;
    float part_img;
} COMPLEX;

This structure has only two members. The first member represents the real part and the second member represents the imaginary part.

The Method

In order to sum any two complex numbers (or to carry out any operations on complex numbers) first we have to have a new data type to handle complex numbers. Let this new data type be COMPLEX. This new data type will have the shape as shown in the previous paragraph.

The necessary structure is defined either before the main( ) or inside the main( ) function. In this example the required structure has been defined before the main( ), just like global variables, and three complex numbers a, b and c have been declared inside the main( ), as usual, using a declaration statement of the form

COMPLEX a, b, c;

The sum of two or more complex numbers is obtained by finding the sum of real parts of all complex numbers and the sum of imaginary parts of all the complex numbers separately. After obtaining the sum of the individual members, the sum number is printed out. The output should appear like part_real ± i part_img. There is no direct method available for this type of output. As such a complex number print function called print_complex( ) has been developed and used for the necessary output operation.

C-Tips

As already mentioned individual members of a structure are accessed using the dot (.) operator. A function called print_complex ( ) has been developed to print the sum, which is also a complex number. Therefore, a structure has to be transmitted to the function. Like arrays, structures are also transmitted by implication. In other words, when structures are used as actual arguments in a calling function, address of the structure is passed on automatically to the called function by the C compiler. Also, as usual, the function prototype has to be used in the main ( ) function. As the print_complex ( ) function is not returning any value, it has been type declared as void.

Flowchart

images

The Program


/* To compute the sum of two complex numbers - passing a structure to
   a function */

#include<stdio.h>
#include<conio.h>
#include<math.h>

typedef struct                            /* Defining a structure */
{
   float part_real;
   float part_img;
}  COMPLEX;                       /* COMPLEX is the new data type*/

main()
{

     COMPLEX a,b,c;            /* Declaring structure variables */
     void print_complex ( COMPLEX x);     /* Function prototype */
     clrscr();

     printf(“Enter first complex number: ”);
                             /* Accepting first complex number */
     scanf(“%f %f”,&a.part_real,&a.part_img);
     /* Printing the first complex number by calling
        print_complex()*/
     printf(“
Complex numberl : ”);
     print_complex(a);
                             /* Accepting second complex number */
     printf(“
Enter second complex number: ”);
     scanf(“%f %f”,&b.part_real,&b.part_img);
     /* Printing the second complex number by calling
        print_complex()*/
  printf(“
Complex number2 = ”);
  print_complex(b);
     c.part_real=a.part_real+b.part_real; /* Computing the sum */
     c.part_img=a.part_img+b.part_img;
                      /* Printing the resultant complex number */
     printf(“
Addition of two complex numbers = ”);

  print_complex(c);         /* Calling print_complex function() */

}

/* Function to print the complex number */
void print_complex(COMPLEX x)
{

      if (x.part_img < 0 )
         printf(“%.2f - i %.2f
”,x.part_real, fabs(x.part_img));
      else
         printf(“%.2f + i %.2f
”,x.part_real,x.part_img);
      return;
}

10.4 ARRAY OF STRUCTURE VARIABLES WITH A STRUCTURE AS MEMBER OF ANOTHER STRUCTURE

A structure can be used as a member of another structure. Such a member structure can be referred to as a substructure. Obviously, both the structure as well as its substructure have to be defined before they are used. A substructure must be defined before its main structure is defined. These definitions can appear either inside the beginning of a main( ) function or before the main ( ).

The Method

Here, one of the examples discussed earlier (in Section 10.2) is considered once again. In this example the three subjects sub1, sub2 and sub3 which were treated as individual members in Section 10.2 have been taken as the members of a substructure called the subjects. The shape of the substructure subjects and the structure student will, now, be as shown in the next page.

images

The required substructure and its main structure have been defined using the typedef and before the main( ). It may be observed that marks is a substructure of the new data type SUBJECTS. This new data type declaration is actually made within the student structure definition.

As in Example 10.2, here also an array of structure variables is processed. First, necessary declarations of the structures and local variables are made. Then all the structure members are given values interactively. The total marks and the percentage of marks are computed using the relations of the form

s[i] .total = s[i].marks.sub1 + s[i].marks.sub2 + s[i].marks.sub3;
s[i]. percent = s[i].total / 3.0;

The computed results are output using the printf ( ) function. The mechanism of accessing a substructure member within an array of structures is shown in the following figure.

images

The Program


/*Structure within a structure (an array of structure variables)*/

#include<stdio.h>
#include<conio.h>

/* Defining structure subjects*/
typedef struct
   {
     int sub1;
     int sub2;
     int sub3;
   } SUBJECTS;

typedef struct                /* Defining the structure student */
   {
     char name[10 0];
     char usn[10];
     SUBJECTS marks;        /* Member marks is of structure type */
     int total;
     float percent;
   } STUDENT;
main()
{
    int i,n;
    STUDENT s[100];        /* Declaring array of structure type */
    clrscr();

    printf(“	Enter the number of students: ”);
    scanf(“%d”,&n);
    printf(“%d”,n);

    for(i=0;i<n;++i)
    {

         getchar();            /* To absorb the newline character */
                             /* Accepting the student details */
     printf(“

	Enter the student name: ”);
     gets(s[i].name);
     printf(“%s”,s[i].name);

     printf(“
	Enter the student University Seat Number: ”);
     gets(s[i].usn);
     printf(“%s”,s[i].usn);

     printf(“
	Enter the marks of subjectl: ”);
     scanf(“%d”,&s[i].marks.sub1);
     printf(“%d”,s[i].marks.sub1);
     printf(“
	Enter the marks of subject2: ”);
     scanf(“%d” ,&s[i].marks.sub2);
     printf(“%d”,s[i].marks.sub2);
     printf(“
	Enter the marks of subject3: ”);
     scanf(“%d”,&s[i].marks.sub3);
     printf(“%d”,s[i].marks.sub3);
                                       /* Computing the total */
     s[i].total = s[i].marks.sub1 + s[i].marks.sub2
                    + s[i].marks.sub3;
     s[i] .percent = s [i] .total / 3.0;
    
    }

    printf(“

	Student Details :

”);
    printf(“	_________________________  __________
”);
    printf(“	Name		    USN		Subj1 	Subj2 	Subj3 	Total	
              Percent 
”);
    printf(“	___________________________________
”);
    for(i=0;i<n;++i)
    {
         /* Printing the students details */
     printf(“	%-20s”,s[i].name);
     printf(“%s”,s[i].usn);
     printf(“		%d”,s[i].marks.sub1);
     printf(“	%d”,s[i].marks.sub2);
     printf(“	%d”,s[i].marks.sub3);
     printf(“	%d”,s[i].total);
     printf(“	%.2f
”,s[i].percent);
    }

}

Note: Arrays could be the members of a structure. For example, the three subjects sub1, sub2 and sub3 which were considered as individual members of a structure in Section 10.2 and as members of a substructure in Section 10.4 can be taken as the elements of an array subjects[ ]. This array can be then used as a member of the structure student as shown below.

struct student
{
    char  name[30];
    char  usn[10];
    int   subjetcs[3];
    int   total;
    float percent;
};

A program similar to the one's discussed in Section 10.2 and 10.4 can be written using the above mentioned shape of the structure.

EXERCISES

  1. Define an employee structure having the employee name, employee number, experience (in years) and salary as its members. Develop a C program to print the names and numbers of all the employees who have more than 3 years of experience and salary less than Rs. 5000/-.
  2. Define a student structure having the name, usn (University Seat Number), marks in five subjects, total and percentage of marks as its members. Marks of all the subjects are to be stored in an array, say marks. Develop a C program to list the names of all the students who have failed.

    [A student is declared as failed if he/ she has scored less than 40 in any of the subjects and less than 45% in aggregate].

  3. Define a book structure having title of the book, ISBN, author, price and month and year of publication as its members. Use a substructure to store the month and year of publication information. Develop a C program to accept a date (in the form of month and year) and list out all the book titles (along with price and ISBN) published during that date.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.117.214