Structure


A structure is a collection of different data types.
It is collection of one or more variable of same data type or dissimilar data types, grouped together under a single name for convenient handing.
Example:-
int --> Interger
char--> char
float --> floating

What is need of structure ?

 Array is collection of similar data types
 i.e
  if we want to store student roll and marks.
  Roll 1 and marks 25 array can store because both are integer.
  But if we would like to store student roll , name marks and percentage.
  Than array not store integer character and floating point, this can be with the help of structure.
  Structure is a collection of different data types.
  roll    name    percentage
   01       raj          45.5
Syntax:-
     struct tag_name
     {
        type 1;
        type 2;
        ………….;
    }struct variable ;
 Note:-structure member can be access with dot(.)

Example:-
   Struct student
 {
    int roll;
   char name[10];
    ………;
  } s1,s2;

Tagged structure

In tagged structure struct can be followed by an identifier this identifier is called tag name. The structure definition associated with a tag name is called tagged structure.
Syntax:-
   Struct tag_name
    {
      type1
      type 2….
    };
  void main()
  {
   struct stu
  {
   int roll;
   char name[10];
  };
   printf(“enter roll”);
   scanf(“%d”,&stu.roll);
   printf(“enter name”);
   scanf(“%c”,stu.name);
   printf(“%d”, roll);
   printf(“%c”,name);
   getch();
  }

Structure without tags.

The structure tags name is optional. The structure definition without tag name is called struct without tags.
Syntax:-
       Struct
      {
        type1
        type 2….
      }stu1,stu2;
  void main()
  {
   struct
  {
   int roll;
   char name[10];
   }stu1,stu2;
   printf(“enter roll of 2 student”);
   scanf(“%d%d”,&stu1.roll,&stu2.roll);
   printf(“enter name of two student”);
   scanf(“%s%s”,stu1.name,stu2.name);
   printf(“%d%d”, stu1.roll,stu2.roll);
   printf(“%s%s”,stu1.name,stu2.name);
   getch();
  }

Type defined structure

 
The structure defintion associated with keyword typedef is call type defined structure. This is the most powerful way of defining the structure.
Syntax:-
Typedef struct
     {
        type1
        type 2…..
     }TYPE_ID

Example:-
     typedef struct
    {
      int roll
     char name[23];
    }student;
 void main()
  {
   typdef struct
  {
   int roll;
   char name[10];
   }stu1,stu2;
   printf(“enter roll of 2 student”);
   scanf(“%d%d”,&stu1.roll,&stu2.roll);
   printf(“enter name of two student”);
   scanf(“%s%s”,stu1.name,stu2.name);
   printf(“%d%d”, stu1.roll,stu2.roll);
   printf(“%s%s”,stu1.name,stu2.name);
   getch();
  }