Structure in C

The structure is also known as the collection of elements with different data types. We can store under a single name, multiple types of elements with different datatype can be saved.

First, we need to define a structure with different members and then by using that structure we need to declare that structure’s variable. Structure variable has access to all the members of the given structure.


 


Steps needed to follow if anyone wants to implement the structure in the C programming language

  • Define Structure
  • Declare that structure variable
  • Initialize the members of that structure
  • Access the members of that variable

DEFINING A STRUCTURE

The syntax for defining any structure variable

Struct Tag name// tag name may be any name

{

Datatype1 variable name1;

Datatype2 variable name2;

.

.

.

.

};

Example (STRUCTURE DEFINITION):

Struct employee

Int number;

Char name[5];

Float Salary;

};

DECLARING STRUCTURE

The syntax for Structure declaration

Struct Employee

Int number;

Char name[5];

Float salary;

}

Struct Employee E1, E2;    »»»»»»»»»»»» Structure declaration

Here, we are declaring one structure variable, which should follow the structure of employee i.e. all the structure variable will be having all the data members.

INITIALIZATION

The structure can be initialized in 2 ways

  • Compile time
  • Run time

Compile time Initialization

We need to initialize each structured variable with the use of assignment operator.

Struct Employee E1= {30,”PQR”, 85.78};

Struct Employee E2= {34,”STU”,97.54};

For Run time Initialization

The structure can be initialized at the runtime with the help of Scanf

For Example:

Scanf(“%d,%S,%F”,&E1.number,E1.name,&E1.salary);


ACCESSING IN STRUCTURE

Accessing can be done with the help of the dot operator. With the use of dot, every structure variable can be able to access its member.

For Example:

If E1 want to access the number then representation will be S1.number;

Coding Tag

Coding Tag always happy to serve you in Information Technology (IT). Learn HTML, CSS, Javascript, PHP, Android, Digital Marketing, Latest IT News and many more.

Leave a Reply

avatar
  Subscribe  
Notify of