C Structure example

Structures in C defines the group of contiguous (adjacent) fields, such as records or control blocks.

C Structure example

C Structure example

     

This section illustrates you the concept of structure in C.

Structures in C defines the group of contiguous (adjacent) fields, such as records or control blocks. A structure is a collection of variables grouped together under a single name. It provides an elegant and powerful way for keeping related data together. 

Structure Declaration:   

struct struct-name{
type field-name; 
type field-name; 
... };

Once the structure is defined, you can declare a structure variable by preceding the variable name by the structure type name. In the given example, a small structure i.e struct is created student and declared three instances of it as shown below.

struct student{
int id;
char *name;
float percentage;
}
  

In structures, we have assigned the values to the instances i.e, id, name, percentage in the following way:

student1.id=1;
student2.name = "Angelina";
student3.percentage = 90.5;

Here is the code:

STRUCTUR.C

#include <stdio.h>
#include <conio.h>

struct student {
  int id;
  char *name;
  float percentage;
student1, student2, student3;
int main() {
  struct student st;
  student1.id=1;
  student2.name = "Angelina";
  student3.percentage = 90.5;
  printf(" Id is: %d \n", student1.id);
  printf(" Name is: %s \n", student2.name);
  printf(" Percentage is: %f \n", student3.percentage);
  getch();
  return 0;
}

Output will be displayed as:

STRUCTUR.EXE

Download Source Code