Ad Code

Responsive Advertisement

structure in c language.

What is Structure? Explain with example
Structure is a user defined data type which is use to store collection of element with
different data type.
Structure is use to encapsulate, or group together different data type.



Syntax 
struct <struct_name>
{
 Datatype mem1;
 Datatype mem2;
 …………………
 }var_name;



Example
 struct student
 {
       int rn;
      char name[20];
      char mf;
      int age;
 };
main()
{
      struct student s;
      clrscr();
       s.rn=11;
       strcpy(s.name,"vimal");
      s.mf='V';
      s.age=26;
     printf("\n Roll No:%d",s.rn);
     printf("\n Name:%s",s.name);
     printf("\n Male Female:%c",s.mf);
     printf("\n Age: %d",s.age);
  getch();
}

How to take input from user with Structure 

struct student 
 {
       int rn;
       char name[20];
       char mf;
     int age;
 }s[3];
main()
{
 int i;
 clrscr();
    for(i=0;i<2;i++)
    {
          printf("Enter roll no:=>");
          scanf("%d",&s[i].rn);
          printf("Enter Name:=>");
         scanf("%s",s[i].name);
         printf("Enter Gender:=>");
         scanf("%s",&s[i].mf);
         printf("Enter age:=>");
       scanf("%d",&s[i].age);
 }
 for(i=0;i<2;i++)
 {
      printf("\n %d \t %s \t %c \t       %d",s[i].rn,s[i].name,s[i].mf,s[i].age);
 }
 getch();
}

Explain Nested Structure with Example. 
-> A structure may have structure as members called nested Structure. It means if a
structure having structure is called nested structure.

main()
{
 struct date
 {
       int d;
       int m;
       int y;
 };
 struct
 {
      int rn;
      char name[20];
      struct date dob;
 }s={1,"vimal",20,1,1986};
 printf("\nRoll no:=>%d",s.rn);
 printf("\nName:=>%s",s.name);
 printf("\n Brithdate:=>%d %d %d",s.dob.d,s.dob.m,s.dob.y);
 getch();
}


Use of structures with function 
-> Structures are user defined data types; function can return structures and also take them
as arguments.
-> To return a structure from a function declares the function to be of the structure type
which is suppose to return.
main()
{
struct student
 {
      int rn;
      char name[20];
 }s={10,"vimal"};
 void test(int , char[]);
 clrscr();
 test(s.rn,s.name);
 getch();
}
void test(int x,char y[])
{
 printf("\n Roll no:=>%d",x);
 printf("\n Name:=>%s",y);
}


To pass entire Structure 

struct student
 {
 int rn;
 char name[20];
 };
 main()
 {
        void test(struct student);
        struct student s={10,"vimal"};
        clrscr();
       test(s);
      getch();
}
void test(struct student s)
{
      printf("\n Roll no:=>%d",s.rn);
      printf("\n Name:=>%s",s.name);
}


Structure with pointer

main()
{
 struct student
 {
       int rn;
       char name[20];
       char gender;
 }s={1,"VIMAL",'M'},*p=&s;
  clrscr();
    printf("\n Roll no:=>%d",p->rn);
    printf("\n Name:=>%s",p->name);
    printf("\n Gender:=>%c",p->gender);
 getch();

Post a Comment

0 Comments