Anda di halaman 1dari 23

Structures

Topics in Structures:-

 Definition or Creating a structure


 Declaration of a structure variable
 Accessing members of a structure
 Student structure example
 Arrays of structures
 Arrays within structures
 Nested structures
 Structure Initialization
 Copying structure variables
 Comparing structure variables
 Pointer to structures or structures with pointers
 Passing structures as function arguments or structures with functions
 Self referential structures

Ordinary variables can store only one value at a time where as array stores a collection of
similar data type elements.

But sometimes it is necessary to store information of different data types as a single unit.

Ex: Student details contains Student no, student name, student average

Employee details contains Employee no, employee name, employee salary

Book details contains Book name, book price, book author, book code

Structure definition:

Structure is a user defined data type. A Structure can be defined as a collection of


heterogeneous data type elements under a single name and all the elements are stored in
adjacent memory locations.

Syntax for defining or declaring or creating a structure:-

struct structure name or tag name

data type1 var1,var2,--------;

data type2 var1,var2,----------;


-------------------------------

--------------------------------

};

struct:- struct keyword is used for defining the structure.

structure name or tag name:- For structure name identifier rules are to be followed.
structure name is nothing but name of the user defined data type.

data type:- The basic data types are int, float, char and double.

members:- The variables which are declared inside a structure are known as members. The
members of a structure must be enclosed in curly braces { }.

Structure definition must ends with semicolon (;).

Example for structure definition:-

struct student

int rno;

char name[20];

int m1,m2,m3;

};

Note: A new data type is created – struct student

Structure variable declaration:-

 Whenever a structure is defined then memory will not be allocated to the members of
the structure.
 For member variables the memory will be allocated only when a structure variable is
declared.
 So, whenever a structure variable is declared then memory will be allocated to the
members of the structure.
 Like normal variables the structure variables are declared before they are used in the
program.

Structure variable can be declared in 2 ways.

1. At the time of creating the structure

struct structure_name

datatype1 var1,var2;

datatype2 var1,var2;

------------------------

------------------------

}structure_variable1, structure_variable2,…………structure_variablen;

Example:

struct student

int no;

char name[20];

float avg;

}s1,s2;

s1 and s2 are two structure variables of struct student type.

2.After creating the structure

struct structure_name

datatype1 var1,var2;

datatype2 var1,var2;

------------------------
------------------------

};

struct structure_name structure_variable1, structure_variable2,……….. structure_variablen;

Example:- struct student s1,s2;

Accessing members of a structure:- The members of a structure can be accessed in 2 ways.

1. Using period or member ship or dot (.) operator


2. Using arrow(->) operator

1.Using period or dot(.) operator:- If the structure variable is an ordinary variable then we
uses dot(.) operator for accessing the members of structure.

Syntax:- structure_variable.member;

Ex:- s1.rno;

s1.name;

s1.m1;

Storing the values in the members of structure:- We can store the values in the members
of structure in 2 ways.

1.Assigning the values:-

s1.rno=10;

s1.m1=90;

strcpy(s1.name,”ramu”);

2.Reading the values from keyboard:-

Syntax:- scanf(“format specifiers” ,&structure_variable.member1,


&structure_variable.member2);

Eg:- scanf(“%d%d%d%d%s”,&s1.rno,&s1.m1,&s1.m2,&s1.m3,&s1.name);

2.Using Arrow(->) operator:- If the structure variable is pointer variable then we uses
arrow(->) operator for accessing the members of structure.

Syntax:- structure_variable->member;

Ex:- s1->rno;
s1->name;

s1->m1;

Storing the values in the members of structure:- We can store the values in the members
of structure in 2 ways.

1.Assigning the values:-

s1->rno=10;

s1->m1=90;

strcpy(s1->name,”ramu”);

2.Reading the values from keyboard:-

Syntax:- scanf(“format specifiers”, &structure_variable->member1, &structure_variable->


member2);

Eg:- scanf(“%d%d%d%d%s”,&s1->rno,&s1->m1,&s1->m2,&s1->m3,&s1->name);

Student structure example or write a c program to access the student data with fields
rno, name, marks and display the student details.

#include<stdio.h>

int main()

struct student

int rollno;

char name[20];

int m1,m2,m3,total;

float avg;

}s1;

printf("\nenter roll no");

scanf("%d",&s1.rollno);

printf("\nenter name");

fflush(stdin);
gets( s1.name);

printf("\nenter 3 subject marks");

scanf("%d%d%d",&s1.m1,&s1.m2,&s1.m3);

s1.total=s1.m1+s1.m2+s1.m3;

s1.avg=(float)s1.total/3;

printf("\nStudent details are\n");

printf("\nRoll no=%d\nName=%s\nM1 marks=%d\nM2 marks=%d\nM3


marks=%d\nTotal=%d\nAverage=%f",s1.rollno,s1.name,s1.m1,s1.m2,s1.m3,s1.total,s1.avg);

return 0;

Result:-

Input:-

enter roll no 10

enter name ramu

enter 3 subject marks 70 80 90

Output:-

Roll no=10

Name=ramu

M1 marks=70

M2 marks=80

M3 marks=90

Total=240

Average=80

Arrays of structures:-

 An array is a collection of similar data type elements.


 In the same way we can also define an Array of structures.
 Several structure variables grouped into one array is referred to as an array of structures.
 To process more records like student details, employee details, faculty details or any
item details we can use the concept called Array of structures.
Syntax1:- struct structur_name structure_variable[size];

Ex1:- struct student s[100];

Syntax2:-

struct structure_name

datatype1 var1,var2;

datatype2 var1,var2;

------------------------

------------------------

}structure_variable1[size], structure_variable2[size],…………structure_variablen[size];

Ex2:-

struct student

int no;

char name[20];

float avg;

}s1[10],s2[10];

struct student s[60]; here s[60] is an array of 60 variables of struct type.

S[0] means first student

S[1] means second student

- --
- --
- --

S[59] means 60th student


Ex:- C program to create employee structure with suitable fields and read employee
data dynamically and display them.

#include<stdio.h>

int main()

struct emp

int empid,sal;

char name[20];

}e[10];

int i,total=0,n;

float avg;

printf("\nenter no of employees");

scanf("%d",&n);

for(i=0;i<n;i++)

printf("\nenter employee %d details",i+1);

printf("\nenter emp id");

scanf("%d",&e[i].empid);

printf("\nenter employee sal\n");

scanf("%d",&e[i].sal);

fflush(stdin);

printf("\nenter employee name\n");


gets(e[i].name);

for(i=0;i<n;i++)

total=total+e[i].sal;

avg=(float)total/n;

for(i=0;i<n;i++)

printf("\nEmployee %d details are",i+1);

printf("\nemp id is %d",e[i].empid);

printf("\nemp name is %s",e[i].name);

printf("\nemp sal is %d",e[i].sal);

printf("\nTotal sal is %d",total);

printf("\nAverage sal is %f",avg);

return 0;

Result:-

Input:-

enter no of employees 2

enter employee 1 details

enter emp id 10

enter employee sal 10000

enter employee name ramesh


enter employee 2 details

enter emp id 20

enter employee sal 20000

enter employee name naresh

Output:-

Employee 1 details are

emp id is 10

emp name is ramesh

emp sal is 10000

Employee 2 details are

emp id is 20

emp name is naresh

emp sal is 20000

Total sal is 30000

Average sal is 15000

Arrays within structures:- An array is a collection of similar data type elements and all the
elements will be stored in adjacent memory locations. We can use arrays with in the
structure.

Ex:-

#include<stdio.h>

int main()

struct student

int rno;
char name[20];

int m[6];

int total;

}s[10];

int i,j,n;

printf("\nenter no of students");

scanf("%d",&n);

for(i=0;i<n;i++)

printf("\nenter student %d details",i+1);

printf("\nenter roll no");

scanf("%d",&s[i].rno);

printf("\nenter name\n");

fflush(stdin);

gets(s[i].name);

printf("\nenter marks\n");

for(j=0;j<6;j++)

scanf("%d",&s[i].m[j]);

for(i=0;i<n;i++)

s[i].total=0;

for(j=0;j<6;j++)

s[i].total=s[i].total+s[i].m[j];

}
for(i=0;i<n;i++)

printf("\nStudent %d details are",i+1);

printf("\nroll no is %d",s[i].rno);

printf("\nname is %s",s[i].name);

printf("\nTotal is %d",s[i].total);

return 0;

Result:-

Input:-

enter no of students 2

enter student 1 details

enter rno 10

enter name ramesh

enter marks 90 91 92 93 94 95

enter student 2 details

enter rno 20

enter name naresh

enter marks 80 81 82 83 84 85

Output:-

Student 1 details are

rollno is 10

name is ramesh

Total is 555

Student 2 details are

rollno is 20
name is naresh

Total is 495

Nested structures:-

A structure within another structure is called as nested structure.


A structure that contains another structure as its members is called as nested structure.
Nested structure can be defined in 2 ways.
1. One structure can be defined in another structure definition
2. Structure variable can be declared as a member of another structure
1.One structure can be defined in another structure definition:-
struct student
{
int rno;
char name[20];
int marks;
struct dob
{
int day,month,year;
};
};
2. Structure variable can be declared as a member of another structure:-
struct dob
{
int day,month,year;
};
struct student
{
int rno;
char name[20];
int marks;
struct dob d;
};
Ex:-
#include<stdio.h>
struct student
{
int student_no;
char name[20];
char course[20];
struct date
{
int day;
int month;
int year;
}d;
}s;
main()
{
printf("\nenter student no\n");
scanf("%d",&s.student_no);
fflush(stdin);
printf("\nenter name\n");
gets(s.name);
printf("\nenter course\n");
gets(s.course);
printf("\nenter day,month and year\n");
scanf("%d%d%d",&s.d.day,&s.d.month,&s.d.year);
printf("\nStudent details are\n");
printf("\nStudent no is %s",s.student_no);
printf("\nName is %s",s.name);
printf("\nCourse is %s",s.couse);
printf("\nDOB is %d-%d-%d",s.d.day,s.d.month,s.d.year);
}
Result:-
Input:-
enter student no 10
enter name ramesh
enter course B.Tech
enter day,month and year 15 8 2000
Output:-
Student details are
Student no is 10
Name is ramesh
Course is B.Tech
DOB is 15-8-2000

Structure Initialization:- We can initialize the members of a structure in 2 ways.

1.Initializing the members of structure in structure definition:-

struct student

int no;

char name[20];

int total;

}s={10,”ramu”,550};

2.Initializing the members of structure at structure variable declaration:-

struct student s={10,”ramu”,550};

Structure assignment (copying one structure to another structure):-


In c, values of one structure variable can be assigned to other variable of same structure.
Ex:
# include <stdio.h>
struct student
{
int no;
char name[20];
float avg;
}s1;
void main()
{
struct student s1={65,”Aditya”,85.45};
struct student s2;
s2=s1;
printf("\nroll no is %d\nname is %s \navg is %f",s2.no,s2.name,s2.avg);
}
Comparing structure variables:- Structure variables can’t be compared directly like
ordinary variables.

Ex:- s1= = s2 - not valid

s1!= s2 --> not valid

But we can compare 2 structure variables by individual members.

Ex:- C program to accept 2 dates from the user and check if they are different dates or same.

#include<stdio.h>

main()

struct date

int day,month,year;

};

struct date d1={16,8,1984};

struct date d2={15,8,1992};

clrscr();

if( (d1.day==d2.day) && (d1.month==d2.month) && (d1.year==d2.year) )

printf("\nDates are same");

else

printf("\nDates are different");

getch();

Output:-

Dates are different


Pointer to structures or Strctures with pointers:-
 In c language pointers can also points to structures.
 It is possible to have pointers pointing to a structure in the same way as pointers
pointing to int, float, char and such pointers are known as structure pointers.
 The structure pointer uses -> indirection operator in order to access structure
members/
Example:
#include <stdio.h>

struct student

int rno;

char name[20];

int marks;

};

void main()

struct student *ptr;

ptr->rno=10;

strcpy(ptr->name,"ramu");

ptr->marks=550;

printf("\nname is %s",ptr->name);

printf("\nrno is %d",ptr->rno);

printf("\nmarks is %d",ptr->marks);

Passing structures as function arguments or structures with functions or structures


with functions:-

We can pass structures as arguments to functions in 2 ways.

1. Passing individual members of the structure as arguments to a function


2. Passing entire structure as argument to a function

1.Passing individual members of the structure as arguments to a function:-

#include<stdio.h>

void display(int,char[]);
int main()

struct student

int rno;

char name[20];

}s;

printf("\nEnter roll no");

scanf("%d",&s.rno);

fflush(stdin);

printf("\nEnter name");

gets(s.name);

display(s.rno,s.name);

return 0;

void display(int rno,char name[20])

printf("\nroll no is %d",rno);

printf("\nname is %s",name);

Result:-

Input:- Enter roll no 10

Enter name ramesh

Output:- roll no is 10

name is ramesh
2.Passing entire structure as argument to a function:-

#include<stdio.h>

struct student

int rno;

char name[20];

}s;

void display(struct student s);

int main()

printf("\nEnter roll no");

scanf("%d",&s.rno);

fflush(stdin);

printf("\nEnter name");

gets(s.name);

display(s);

return 0;

void display(struct student s)

printf("\nroll no is %d",s.rno);

printf("\nname is %s",s.name);

Result:-

Input:- Enter roll no 10

Enter name ramesh

Output:- roll no is 10
name is ramesh

Ex:-Write a c program to add and subtract 2 complex numbers

#include<stdio.h>

#include<conio.h>

struct complex

int real,imag;

}c1,c2,c3;

void add(struct complex c1,struct complex c2);

void subtract(struct complex c1,struct complex c2);

int main()

printf("\nEnter 1st complex number\n");

scanf("%d%d",&c1.real,&c1.imag);

printf("\nEnter 2nd complex number\n");

scanf("%d%d",&c2.real,&c2.imag);

add(c1,c2);

subtract(c1,c2);

return 0;

void add(struct complex c1,struct complex c2)

c3.real=c1.real+c2.real;

c3.imag=c1.imag+c2.imag;

printf("\nAddition=%d+i%d",c3.real,c3.imag);

}
void subtract(struct complex c1,struct complex c2)

c3.real=c1.real-c2.real;

c3.imag=c1.imag-c2.imag;

printf("\nSubtraction=%d-i%d",c3.real,c3.imag);

Result:-

Input:- enter 1st complex number 4 6

Enter 2nd complex number 2 4

Output:-

Addition=6+i10

Subtractiob= 2-i2

Self referential structures:-

 A structure which contains a pointer to itself is known as “self referential structures”.


 The best example for self referential structures is “linked list”.

Linked list:-It is a collection of nodes which are not necessary to be in adjacent memory
locations.

Each node contains 2 fields.

1. Data Field

2. Next field ( or ) pointer field ( or ) address field

Data field:- Data field contains values like 9, 6.8, ‘a’ , “ramu” , 9849984900

Next field:- It contains address of its next node. The last node next field contains NULL
which indicates end of the linked list.

Diagrammatic representation of linked list:-

10 2000 20 3000 30 NULL

1000 2000 3000


Types of linked list:-

1. Single linked list (or) singly linked list

2. Circular linked list (or) circular single linked list

3. Double linked list

4. Circular double linked list

C program to implement linked list:-

#include<stdio.h>

main()

struct node

int data;

struct node *address;

};

struct node *first,*second,*third,*ptr;

printf("\nEnter first node\n");

scanf("%d",&first->data);

printf("\nenter second node\n");

scanf("%d",&second->data);

printf("\nThird node\n");

scanf("%d",&third->data);

first->address=second;

second->address=third;

third->address=NULL;

ptr=first;

while(ptr!=NULL)

{
printf("%d->",ptr->data);

ptr=ptr->address;

Result:-

Input:- enter first node 10

enter second node 20

enter third node 30

Output:- 10->20->30

--------------------------------------------------------------------------------------------------------------

Anda mungkin juga menyukai