Thursday 28 July 2016

Structure Template

Structure

  • Structure is a collection of elements of different data type under a single name.


Structure Template:

  • A structure is declared using the keyword struct followed by the structure name (tagname).

       struct   tagname
       {
               datatype member1;
               datatype member2;
               :
               :
               :
               datatype memberN;
        };  


Here,
  • Declaring a structure creates a template that describes the characteristics of its members.
  • struct  is a keyword.
  • tagname is the structure name.
  • Here struct tagname becomes the datatype.
  • member1, member2,.... memberN are the members of the structure.
  • So, structure variables can be declared using struct tagname.
  • The elements of a structure are referred as members.
  • Every structure template should end with semicolon.
  • Declaration of the structure template does not reserve any space in memory for the members; space is reserved only when variables of this structure type are declared.
  • Members are not variables; they don't have any existence till they are attached with a structure variable.
  • Member names inside a structure should be different from one another; but these names can be similar to any other variable name declared outside the structure.
  • Member names inside 2 different structures can also be same.
  • Structure template can be declared gloably / locally. 

Example:

#include<stdio.h>
struct student
{
            char name[20];
            int rollno;
            float mark;
};
main()
{
            struct student S1;
            printf("\nEnter name rollno and mark of a student:");
            scanf("%s %d %f", S1.name, &S1.rollno, &S1.mark );
            printf("\n Name is %s \n Rollno is %d \n Mark is %f", S1.name, S1.rollno, S1.mark );
}

Output:
Enter name rollno and mark of a student: aaa 21 98
Name is aaa
Rollno is 21
Mark is 98.000000