Structure is basically a user defined datatype which is a collection of heterogeneous elements.
Each element of a structure is called a member.
It works like a template in C++ and class in Java.
It is used to store student information, employee information, product information, book information etc.
Defining structure
The struct keyword is used to define structure. syntax to define structure in c is:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example of structure to store information of many employees.
#include <stdio.h>
#include <string.h>
struct employee
{ int id;
char name[30];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
e1.id=101;
strcpy(e1.name, "Pranav Chhabra");
e1.salary=56000;
e2.id=102;
strcpy(e2.name, "Abhishek Kumar ");
e2.salary=126000;
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);
//printing second employee information
printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Pranav Chhabra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : Abhishek Kumar
employee 2 salary : 126000.000000
0 Comment(s)