Tuesday, 8 June 2021

Introduction to Structures in C

A structure is a user defined data type which stores different types of data under single name. In C language a structure a structure can be created using "struct" keyword. It has the following syntax.

Storage-class struct tag-name

{

structure members;

};

In the above syntax storage class and tag name are optional but the semicolon at the end of the syntax is compulsory.

Example:

struct employee

{

char name[20];

int DOB;

float salary;

char address[200];

};


 

To initialize and access structure members we use structure variable. A structure variable can be created int two different ways.

1. At the end of the structure syntax 

You can create any number of structure variables to manipulate structure. Before ending of the structure syntax write how many variable. You need by simply writing their name.

Example:

struct employee

{

char name[20];

int DOB;

float salary;

char address[200];

}s1,s2,s3;

2. After the structure declaration

You can also create structure variables individually that is without including structure syntax. To create a structure variable individually we use the following syntax.

Syntax: struct tag-name variable1, variable2,......variable-N;

Example: struct employee e1,e2,e3;

  Initializing structure:

To initialize structure members we use structure variable  

Example:

struct employee

{

char name[20];

int DOB;

float salary;

char address[200];

}e={" Hari", 09/09/1970,$102.7, "VNK", AP,India"};

Accessing structure members

Each members of a  structure can be accessed just like a normal variable. To access structure members the dot operator is use along with structure variable in the following form

structure-variable.structure-member;

Example: Write a C program to read details of student and print them.

#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int no;
int sub1,sub2,sub3;
}s;
void main()
{
printf(" enter student name");
gets(s.name);
printf(" enter hall ticket number");
scanf("%d",&s.no);
printf(" enter marks");
scanf("%d%d%d",&s.sub1,&s.sub2,&s.sub3);
printf(" student details are");
printf("Name=%s", s.name);
printf( Hall ticket number=%d",s.no);
printf(" marks=%d%d%d", s.sub1,s.sub2,s.sub3);
getch();
}

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top