By using arrays we can store items of single data type. Student id ( roll number ) , name , mark ,class are different data types but they belong to same entity student. Here we can declare a structure to store all details of the student which consist of different data types.
Declaring structure variables.
int main()
{
struct Students{
int id;
char name[50];
float mark[5];
};
struct Students s1,s2;
struct Students s3={5,"Ronn",12.5};
return 0;
}
Here s1,s2,s3 are variables of type struct Students. Students is the tagname. We used this tagname to create struct Variables.
Structure is declared to create an template only, we can't initialize the structure at the time of declaring it.
This is not allowed.
struct Students{
int id=1; // Not valid
char name[50]="Ravi"; // Not valid
float mark[5]=4.5; // Not valid
};
Assigning data to struct variables
We can read user input and assing the data to struct variables.
int main()
{
struct Students{
int id;
char name[50];
float mark;
};
struct Students s1,s2;
printf("\nEnter ID :");
scanf("%d",&s2.id);
printf("\nEnter name :");
scanf("%s",&s2.name);
printf("\nEnter mark :");
scanf("%f",&s2.mark);
// Input over now display data ///
printf("\n\n ID: %d",s2.id);
printf("\n name: %s",s2.name);
printf("\n mark: %f",s2.mark);
return 0;
}
Array of structure
Using array we store user entered data and display the same. Similarly we can create array of structure for struct variables.
int main()
{
struct Students{
int id;
char name[50];
float mark;
}std[2];
int i;
for(i=0;i<2;i++){
printf("\nEnter ID :");
scanf("%d",&std[i].id);
printf("\nEnter name :");
scanf("%s",&std[i].name);
printf("\nEnter mark :");
scanf("%f",&std[i].mark);
}
// Input is over , now display ///
for(i=0;i<2;i++){
printf("\n\n ID: %d",std[i].id);
printf("\n name: %s",std[i].name);
printf("\n mark: %f",std[i].mark);
}
return 0;
}
We can directly assign data to struct variable ( without any user input )
int main()
{
struct Students{
int id;
char name[50];
float mark;
};
int i;
struct Students std[2]={
{1,"Ronn",5.6},
{2,"Geek",7.3}
};
// Input is over , now display ///
for(i=0;i<2;i++){
printf("\n\n ID: %d",std[i].id);
printf("\n name: %s",std[i].name);
printf("\n mark: %f",std[i].mark);
}
return 0;
}