C Programming Tutorial

Advertisements

Nested Structure in C

When a structure contains another structure, it is called nested structure. For example,we have two structures named Address and Employee. To make Address nested to Employee, we have to define Address structure before and outside Employee structure and create an object of Address structure inside Employee structure.

Syntax for structure within structure or nested structure


              struct structure1
              {
                     - - - - - - - - - -
                     - - - - - - - - - -
              };

              struct structure2
              {
                     - - - - - - - - - -
                     - - - - - - - - - -
                     struct structure1 obj;
              };

Example for structure within structure or nested structure


       #include<stdio.h>

       struct Address
       {
              char HouseNo[25];
              char City[25];
              char PinCode[25];
       };

       struct Employee
       {
           int Id;
           char Name[25];
           float Salary;
           struct Address Add;
       };

       void main()
       {
              int i;
              struct Employee E;

              printf("\n\tEnter Employee Id : ");
              scanf("%d",&E.Id);

              printf("\n\tEnter Employee Name : ");
              scanf("%s",&E.Name);

              printf("\n\tEnter Employee Salary : ");
              scanf("%f",&E.Salary);

              printf("\n\tEnter Employee House No : ");
              scanf("%s",&E.Add.HouseNo);

              printf("\n\tEnter Employee City : ");
              scanf("%s",&E.Add.City);

              printf("\n\tEnter Employee House No : ");
              scanf("%s",&E.Add.PinCode);

              printf("\nDetails of Employees");
              printf("\n\tEmployee Id : %d",E.Id);
              printf("\n\tEmployee Name : %s",E.Name);
              printf("\n\tEmployee Salary : %f",E.Salary);
              printf("\n\tEmployee House No : %s",E.Add.HouseNo);
              printf("\n\tEmployee City : %s",E.Add.City);
              printf("\n\tEmployee House No : %s",E.Add.PinCode);

       }


   Output :

                     Enter Employee Id : 101
                     Enter Employee Name : Suresh
                     Enter Employee Salary : 45000
                     Enter Employee House No : 4598/D
                     Enter Employee City : Delhi
                     Enter Employee Pin Code : 110056

              Details of Employees
                     Employee Id : 101
                     Employee Name : Suresh
                     Employee Salary : 45000
                     Employee House No : 4598/D
                     Employee City : Delhi
                     Employee Pin Code : 110056

				

Related topics

Advertisement