SlideShare uma empresa Scribd logo
1 de 55
STRUCTURE
BY:ER.ANUPAMSHARMA
Contents:
• Introduction
• Array of Structure
• Pointer to Structure
• Nested Structure
• PassingStructure to Function
INTRODUCTION TO
STRUCTURE
• Problem:
– How to group together a collection of data items
of different types that are logically related to a
particular entity??? (Array)
Solution: Structure
STRUCTU
RE
 different data types under asinglename.
 The variables are called members of
the structure.
 Thestructure isalso called auser-defined data type.
3
• A structure is a collection of variables of
DEFINING A
STRUCTURE
4
• Syntax:
struct structure_name
{
data_type member_variable1;
data_type member_variable2;
………………………………;
data_type member_variableN;
};
Oncestructure_name is declared asnew data type, then
variables of that typecanbe declared as:
struct structure_name structure_variable;
Note: The members of a structure do not occupy memory
until they are associatedwith a structure_variable.
5
• Example
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long intphone_no;
};
struct student st;
• Multiple variables of struct student type canbe declared
as:
struct student st1, st2,st3;
DEFINING A
STRUCTURE…
6
• Each variable of structure has its own copy of
member variables.
• The member variables are accessed using the
dot (.) operator or memberoperator.
• For example: st1.name is member variable
name of st1 structure variable while
st3.gender is member variable gender of st3
structure variable.
DEFINING A
STRUCTURE…
7
• The structure definition
variable declaration can
combined as:
struct student
{
charname[20];
int roll_no;
float marks;
char gender;
long intphone_no;
}st1, st2,st3;
The use of structure_name isand
be optional.
struct
{
charname[20];
int roll_no;
float marks;
char gender;
long intphone_no;
}st1, st2,st3;
STRUCTURE
INITIALIZATION
8
• Syntax:
structstructure_namestructure_variable={value1, value2, …, valueN};
• There is a one-to-one correspondenc
e
between the members and their initializing
values.• Note: C does not allow the initialization of
individual structure members within the
structure definition template.
struct student
{
charname[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
void main()
{
struct student st1={“ABC", 4, 79.5, 'M', 5010670};
clrscr();
printf("NametttRoll No.tMarksttGendertPhone No.");
printf("n.........................................................................n");
printf("n %stt %dtt %ft%ct %ld", st1.name, st1.roll_no, st1.marks,
st1.gender, st1.phone_no);
getch();
}
9
PARTIAL
INITIALIZATION
10
• We can initialize the first few members and
leave the remainingblank.
• However, the uninitialized members should be
only at the end of the list.
• The uninitialized members are assigned
default values asfollows:
– Zero for integer and floating pointnumbers.
– ‘0’ for characters andstrings.
11
struct student
{
charname[20];
int roll;
char remarks;
float marks;
};
void main()
{
struct student s1={“name", 4};
clrscr();
printf("Name=%s", s1.name);
printf("n Roll=%d", s1.roll);
printf("n Remarks=%c",s1.remarks);
printf("n Marks=%f", s1.marks);
getch();
}
ACCESSING MEMBER OF
STRUCTURE/ PROCESSING
A STRUCTURE
12
• By using dot (.) operator or period operator or
member operator.
• Syntax:
structure_variable.member
• Here, structure_variable refers to the name of
a struct type variable and member refers to
the name of amember within thestructure.
QUESTIO
N
13
• Create a structure named student that has
name, roll and mark as members. Assume
appropriate types and size of member. Write a
program using structure to read and display
the data entered by theuser.
14
struct student
{
charname[20];
int roll;
float mark;
};
voidmain()
{
struct student s;
clrscr();
printf("Enter name:t");
gets(s.name);
printf("n Enter roll:t");
scanf("%d", &s.roll);
printf("n Enter marks:t");
scanf("%f", &s.mark);
printf("n Name t Roll t Markn");
printf("n...................................n");
printf("n%st%dt%f", s.name, s.roll,s.mark);
getch();
}
COPYINGAND COMPARING
STRUCTURE
VARIABLES
15
• Twovariables of the samestructure type canbe copied in
the sameway asordinary variables.
• If student1 and student2 belong tothe samestructure, then
the following statements arevalid:
student1=student2;
student2=student1;
• However, the statements suchas:
student1==student2
student1!=student2
are not permitted.
• If we need to compare the structure variables, we may do
soby comparing members individually.
STRUCT
STUDENT
{
charname[20];
int roll;
};
void main()
{
struct student student1={“ABC",4,};
struct student student2;
clrscr();
student2=student1;
printf("nStudent2.name=%s", student2.name);
printf("nStudent2.roll=%d", student2.roll);
if(strcmp(student1.name,student2.name)==0 &&
(student1.roll==student2.roll))
{
printf("nn student1 and student2 aresame.");
}
getch();
} 16
Here, structure has beendeclared
global i.e.outside of main()
function. Now, any function can
access it and create a structure
variable.
HOW STRUCTURE ELEMENTS ARE
STORED?
17
• The elements of a structure are always stored in
contiguous memory locations.
• A structure variable reserves number of bytes
equal to sum of bytes needed to each of its
members.
• Computer stores structures using the concept of
“word boundary”. In a computer with two bytes
word boundary, the structure variables are stored
left aligned and consecutively one after the other
(with at most one byte unoccupied in between
them called slackbyte).
HOW STRUCTURE ELEMENTS ARE
STORED?
18
• When we declare structure variables, each
one of them may contain slack bytes and the
values stored in such slack bytes are
undefined.
• Due to this, even if the members of two
variables are equal, their structures do not
necessarily compare.
• That’s why C does not permit comparison of
structures.
ARRAY OF
STRUCTURE
19
• Let usconsider we have astructure as:
struct student
{
char name[20];
int roll;
char remarks;
floatmarks;
};
• If we want to keep record of 100 students, we have to make 100
structure variables like st1, st2,…,st100.
• In this situation we can use array of structure to store the records of
100 students which is easier and efficient to handle (because loops
canbe used).
ARRAY OF
STRUCTURE…
20
• Two ways to
declare an
array of structure:
 structstudent
{
char
name[20];
introll;
char
remarks;
float
marks;
}st[100];
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
struct studentst[100];
READING
VALUES
for(i=0; i<5; i++)
{
printf("n Enter rollnumber:");
scanf("%d", &s[i].roll_no);
printf("n Enter first name:");
scanf("%s", &s[i].f_name);
printf("n Enter Lastname:");
scanf("%s", &s[i].l_name);
}
SORTING
VALUES
for(i=0; i<5;i++)
{
for(j=i+1; j<5; j++)
{
if(s[i].roll_no<s[j].roll_no)
{
temp =s[i].roll_no;
s[i].roll_no=s[j].roll_no;
s[j].roll_no=temp;
}
}
}
QUESTIO
N
23
• Define a structure of employee having data
members name, address, age and salary. Take
the data for n employees in an array and find
the averagesalary.
• Write a program to read the name, address,
and salary of 5 employees using array of
structure. Display information of each
employee in alphabetical order of theirname.
ARRAY WITHIN
STRUCTURE
24
• Wecanusesingle or multi dimensional arrays of
type int or float.
• E.g. struct student
{
char name[20];
introll;
float marks[6];
};
struct students[100];
ARRAY WITHIN
STRUCTURE…
25
member
marks[0],
marks contains six
marks[1],
marks obtained in
…, marks[5]
six different
• Here, the
elements,
indicating
subjects.
• These elements can be accessed using
appropriate subscripts.
• For example, s[25].marks[3] refers to the
marks obtained in the fourth subject by the
26th student.
for(i=0;i<n;i++)
{
printf("n Enter information aboutstudent%d",i+1);
printf("n Name:t");
scanf(" %s", s[i].name);
printf("n Class:t");
scanf("%d", &s[i]._class);
printf("n Section:"); scanf("
%c", &s[i].section);
printf("n Input marks of 6subjects:t");
for(j=0;j<6;j++)
{
scanf("%f", &temp);
s[i].marks[j]=temp;
}
} 27
VALUES
STRUCTURE WITHINANOTHERSTRUCTURE
(NESTED STRUCTURE)
27
• Let us consider a structure personal_record to
store the information of apersonas:
• struct personal_record
{
char name[20];
intday_of_birth;
intmonth_of_birth;
int year_of_birth;
float salary;
}person;
STRUCTURE WITHINANOTHERSTRUCTURE
(NESTED STRUCTURE)…
28
• In the structure above, we cangroup all the items related to birthday
together and declare them under asubstructureas:
struct Date
{
int day_of_birth;
intmonth_of_birth;
int year_of_birth;
};
struct personal_record
{
char name[20];
struct Datebirthday;
float salary;
}person;
STRUCTURE WITHINANOTHERSTRUCTURE
(NESTED STRUCTURE)…
29
• Here, the structure personal_record contains a member
named birthday which itself is a structure with 3
members. Thisis called structure within structure.
• The members contained within the inner structure can be
accessedas:
person.birthday.day_of_birth
person.birthday.month_of_birth
person.birthday. year_of_birth
• The other members within the structure personal_record
are accessedasusual:
person.name
person.salary
30
printf("Enter name:t");
scanf("%s", person.name);
printf("nEnter day ofbirthday:t");
scanf("%d", &person.birthday.day_of_birth);
printf("nEnter month of birthday:t");
scanf("%d", &person.birthday.month_of_birth);
printf("nEnter year of birthday:t");
scanf("%d", &person.birthday.year_of_birth);
printf("nEnter salary:t");
scanf("%f", &person.salary);
STRUCTURE WITHINANOTHERSTRUCTURE
(NESTED STRUCTURE)…
31
• Note:- More than onetype of structurescan
benested…
32
struct date
{
int day;
intmonth;
int year;
};
structname
{
char first_name[10];
charmiddle_name[10];
charlast_name[10];
};
structpersonal_record
{
float salary;
struct datebirthday,deathday;
struct namefull_name;
};
POINTER TO
STRUCTURE
33
• Astructure type pointer variable canbe declared as:
struct book
{
charname[20];
int pages;
float price;
};
structbook *bptr;
• However, this declaration for a pointer to structure does not allocate any memory for a
structure but allocates only for a pointer, so that to access structure’s members
through pointer bptr, we must allocate the memory using malloc()function.
• Now, individual structure members are accessedas:
bptr->name bptr->pages bptr->price
(*bptr).name (*bptr).pages (*bptr).price
• Here, ->is called arrow operator and there must be apointer to the structure on the
left side of thisoperator.
34
struct book *bptr;
bptr=(struct book *)malloc(sizeof(structbook));
printf("n Entername:t");
scanf("%s", bptr->name);
printf("n Enter no. ofpages:t");
scanf("%d", &bptr->pages);
printf("n Enter price:t");
scanf("%f", & bptr->price=temp)
POINTER TO
STRUCTURE…
35
• Also, the address of astructure type variable canbe
stored in astructure type pointer variableasfollows:
struct book
{
char name[20];
int pages;
float price;
};
struct book b,*bptr;
bptr=&b;
• Here, the baseaddressof b is assignedtobptr pointer.
POINTER TO
STRUCTURE…
36
• Now the members of the structure book can
be accessedin 3 waysas:
b.name bptr->name (*bptr).name
b.pages bptr->pages (*bptr).pages
b.price bptr-> price (*bptr).price
POINTER TO ARRAY OF
STRUCTURE
37
• Let we haveastructure asfollows:
struct book
{
char name[20];
intpages;
float price;
};
struct book b[10],*bptr;
• Then the assignment statement bptr=b; assigns
the address of the zeroth element of b to bptr.
POINTER TO ARRAY OF
STRUCTURE…
38
• Themembers of b[0] canbe accessedas:
bptr->name bptr->pages bptr->price
• Similarly members of b[1] canbe accessedas:
(bptr+1)->name (bptr+1)->pages (bptr+1)->price
• Thefollowing for statement canbe used to print
all the values of array of structure b as:
for(bptr=b;bptr<b+10;bptr++)
printf(“%s %d %f”, bptr->name, bptr->pages, bptr-
>price);
PROBLE
M
39
• Define a structure of employee having data
members name, address, age and salary. Take
data for n employee in an array dynamically
and find the averagesalary.
• Define a structure of student having data
members name, address, marks in Clanguage,
and marks in information system. Take data
for n students in an array dynamically and find
the total marksobtained.
FUNCTION AND
STRUCTURE
40
• Wewill consider four caseshere:
– Passingthe individual membersto functions
– Passingwhole structure to functions
– Passingstructure pointer to functions
– Passingarray of structure to functions
41
Passing structure member tofunctions
• Structure members can be passed to functions
as actual arguments in function call like
ordinary variables.
• Problem: Hugenumber of structuremembers
• Example: Let us consider a structure employee
having members name, id and salary and pass
these members to afunction:
display(emp.name,emp.id,emp.salary);
VOID DISPLAY(CHAR E[],INT ID ,FLOAT
SAL)
{
printf("nNamettIDttSalaryn);
printf("%st%dt%.2f",e,id,sal);
}
PASSING WHOLE STRUCTURE TO
FUNCTIONS
 Whole structure canbe passedto afunction by the
syntax:
 function_name(structure_variable_name);
 Thecalled function hasthe form:
 return_typefunction_name(structtag_name
structure_variable_name)
 {
 … … … … …;
 }
45
DISPLAY(EMP);
void display(struct employeee)
{
printf("nNametIDtSalaryn");
printf("%st%dt%.2f",e.name,e.id,e.salar);
}
PASSING STRUCTURE POINTER TOFUNCTIONS
• In this case, address of structure variable is
passedasan actual argument to afunction.
• The corresponding formal argument must be a
structure type pointer variable.
• Note: Any changes made to the members in
the called function are directly reflected in the
calling function.
47
DISPLAY(&EMP);
void display(struct employee*e)
{
printf("nNametIDtSalaryn");
printf("%st%dt%.2f",e->name,e->id,e->salary);
}
• Passing an array of structure type to a
function is similar to passing an array of any
type to afunction.
• That is, the name of the array of structure is
passed by the calling function which is the
baseaddress of the array ofstructure.
• Note: The function prototype comes after the
structure definition.
49
PASSINGARRAY OF STRUCTURES TO
FUNCTION
DISPLAY(EMP); //EMP IS ARRAY NAME OF SIZE 2
void display(struct employee ee[])
{
int i;
printf("n Namett IDtt Salaryn");
for(i=0;i<2;i++)
{
printf("%stt%dtt%.2fn",ee[i].name,ee[i].id,ee[i].salary);
}
}
TYPEDEF STATEMENT
 U s e r Defined Data Types
The C language provides a facility called typedef for
creating synonyms for previously defined data type names.
For example, the declaration:
typedef int Length;
makes the name Length a synonym (or alias) for the data
type int.
TYPEDEF(CONT
D.)
 T h e data “type” name Length can now be used in
declarations in exactly the same way that the
data type int can be used:
Length a, b, len ;
Length numbers[10] ;
UNION
 Union has members of different data
types, but canhold data of only one member
at a time.
 T h e different members share the same
memory location.
 T h e total memory allocated to the union is
equal tothe maximum size of the member.
EXAMPLE
#include <stdio.h> union
marks
{
float percent;
char grade;
};
int main ( )
{
union marks student1;
student1.percent = 98.5;
printf( "Marks are %f address is %16lun", student1.perc ent,
&student1.percent);
student1.grade = 'A';
printf( "Grade is %c address is %16lun",student1.grade,
&student1.grade); }
ENUMERATED DATATYPE
Enumeration is a user-defined data type. It is
defined using the keyword enum and the syntax
is:
enum tag_name {name_0, …,name_n} ;
 T h e tag_name is not used directly. The names in
the braces are symbolic constants that take on
integer values from zero through n.
ENUMERATED(CONT
D.)
As an example, thestatement:
enum colors { red, yellow, green } ;
creates three constants.
red is assigned the value 0,
yellow is assigned 1and
green is assigned 2.
Structure in C language

Mais conteúdo relacionado

Mais procurados (20)

Strings
StringsStrings
Strings
 
Enums in c
Enums in cEnums in c
Enums in c
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
structure and union
structure and unionstructure and union
structure and union
 
String c
String cString c
String c
 
Strings in c
Strings in cStrings in c
Strings in c
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
C pointer
C pointerC pointer
C pointer
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Structure c
Structure cStructure c
Structure c
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
String in c programming
String in c programmingString in c programming
String in c programming
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
 

Semelhante a Structure in C language

CA2_CYS101_31184422012_Arvind-Shukla.pptx
CA2_CYS101_31184422012_Arvind-Shukla.pptxCA2_CYS101_31184422012_Arvind-Shukla.pptx
CA2_CYS101_31184422012_Arvind-Shukla.pptxArvindShukla81
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.pptshivani366010
 
358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7sumitbardhan
 
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...Smit Shah
 
Data Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxData Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxGIRISHKUMARBC1
 

Semelhante a Structure in C language (20)

1. structure
1. structure1. structure
1. structure
 
CA2_CYS101_31184422012_Arvind-Shukla.pptx
CA2_CYS101_31184422012_Arvind-Shukla.pptxCA2_CYS101_31184422012_Arvind-Shukla.pptx
CA2_CYS101_31184422012_Arvind-Shukla.pptx
 
637225564198396290.pdf
637225564198396290.pdf637225564198396290.pdf
637225564198396290.pdf
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
structures.ppt
structures.pptstructures.ppt
structures.ppt
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.ppt
 
Session 6
Session 6Session 6
Session 6
 
358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7
 
User defined data types.pptx
User defined data types.pptxUser defined data types.pptx
User defined data types.pptx
 
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
 
CP Handout#10
CP Handout#10CP Handout#10
CP Handout#10
 
Unit4
Unit4Unit4
Unit4
 
C Language Unit-4
C Language Unit-4C Language Unit-4
C Language Unit-4
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
 
03 structures
03 structures03 structures
03 structures
 
Data Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxData Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptx
 
DS_PPT.pptx
DS_PPT.pptxDS_PPT.pptx
DS_PPT.pptx
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
 
DS_PPT.ppt
DS_PPT.pptDS_PPT.ppt
DS_PPT.ppt
 
Structures
StructuresStructures
Structures
 

Mais de CGC Technical campus,Mohali

Mais de CGC Technical campus,Mohali (20)

Gender Issues CS.pptx
Gender Issues CS.pptxGender Issues CS.pptx
Gender Issues CS.pptx
 
Intellectual Property Rights.pptx
Intellectual Property Rights.pptxIntellectual Property Rights.pptx
Intellectual Property Rights.pptx
 
Cyber Safety ppt.pptx
Cyber Safety ppt.pptxCyber Safety ppt.pptx
Cyber Safety ppt.pptx
 
Python Modules .pptx
Python Modules .pptxPython Modules .pptx
Python Modules .pptx
 
Dynamic allocation
Dynamic allocationDynamic allocation
Dynamic allocation
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 
Operators in c by anupam
Operators in c by anupamOperators in c by anupam
Operators in c by anupam
 
Datatypes in c
Datatypes in cDatatypes in c
Datatypes in c
 
Fundamentals of-computer
Fundamentals of-computerFundamentals of-computer
Fundamentals of-computer
 
Searching
Searching Searching
Searching
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Intro
IntroIntro
Intro
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Function in c
Function in cFunction in c
Function in c
 
string in C
string in Cstring in C
string in C
 
C arrays
C arraysC arrays
C arrays
 
Data processing and Report writing in Research(Section E)
Data processing and Report writing in Research(Section E)Data processing and Report writing in Research(Section E)
Data processing and Report writing in Research(Section E)
 
data analysis and report wring in research (Section d)
data analysis and report wring  in research (Section d)data analysis and report wring  in research (Section d)
data analysis and report wring in research (Section d)
 
Section C(Analytical and descriptive surveys... )
Section C(Analytical and descriptive surveys... )Section C(Analytical and descriptive surveys... )
Section C(Analytical and descriptive surveys... )
 

Último

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Último (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

Structure in C language

  • 1. STRUCTURE BY:ER.ANUPAMSHARMA Contents: • Introduction • Array of Structure • Pointer to Structure • Nested Structure • PassingStructure to Function
  • 2. INTRODUCTION TO STRUCTURE • Problem: – How to group together a collection of data items of different types that are logically related to a particular entity??? (Array) Solution: Structure
  • 3. STRUCTU RE  different data types under asinglename.  The variables are called members of the structure.  Thestructure isalso called auser-defined data type. 3 • A structure is a collection of variables of
  • 4. DEFINING A STRUCTURE 4 • Syntax: struct structure_name { data_type member_variable1; data_type member_variable2; ………………………………; data_type member_variableN; }; Oncestructure_name is declared asnew data type, then variables of that typecanbe declared as: struct structure_name structure_variable; Note: The members of a structure do not occupy memory until they are associatedwith a structure_variable.
  • 5. 5 • Example struct student { char name[20]; int roll_no; float marks; char gender; long intphone_no; }; struct student st; • Multiple variables of struct student type canbe declared as: struct student st1, st2,st3;
  • 6. DEFINING A STRUCTURE… 6 • Each variable of structure has its own copy of member variables. • The member variables are accessed using the dot (.) operator or memberoperator. • For example: st1.name is member variable name of st1 structure variable while st3.gender is member variable gender of st3 structure variable.
  • 7. DEFINING A STRUCTURE… 7 • The structure definition variable declaration can combined as: struct student { charname[20]; int roll_no; float marks; char gender; long intphone_no; }st1, st2,st3; The use of structure_name isand be optional. struct { charname[20]; int roll_no; float marks; char gender; long intphone_no; }st1, st2,st3;
  • 8. STRUCTURE INITIALIZATION 8 • Syntax: structstructure_namestructure_variable={value1, value2, …, valueN}; • There is a one-to-one correspondenc e between the members and their initializing values.• Note: C does not allow the initialization of individual structure members within the structure definition template.
  • 9. struct student { charname[20]; int roll_no; float marks; char gender; long int phone_no; }; void main() { struct student st1={“ABC", 4, 79.5, 'M', 5010670}; clrscr(); printf("NametttRoll No.tMarksttGendertPhone No."); printf("n.........................................................................n"); printf("n %stt %dtt %ft%ct %ld", st1.name, st1.roll_no, st1.marks, st1.gender, st1.phone_no); getch(); } 9
  • 10. PARTIAL INITIALIZATION 10 • We can initialize the first few members and leave the remainingblank. • However, the uninitialized members should be only at the end of the list. • The uninitialized members are assigned default values asfollows: – Zero for integer and floating pointnumbers. – ‘0’ for characters andstrings.
  • 11. 11 struct student { charname[20]; int roll; char remarks; float marks; }; void main() { struct student s1={“name", 4}; clrscr(); printf("Name=%s", s1.name); printf("n Roll=%d", s1.roll); printf("n Remarks=%c",s1.remarks); printf("n Marks=%f", s1.marks); getch(); }
  • 12. ACCESSING MEMBER OF STRUCTURE/ PROCESSING A STRUCTURE 12 • By using dot (.) operator or period operator or member operator. • Syntax: structure_variable.member • Here, structure_variable refers to the name of a struct type variable and member refers to the name of amember within thestructure.
  • 13. QUESTIO N 13 • Create a structure named student that has name, roll and mark as members. Assume appropriate types and size of member. Write a program using structure to read and display the data entered by theuser.
  • 14. 14 struct student { charname[20]; int roll; float mark; }; voidmain() { struct student s; clrscr(); printf("Enter name:t"); gets(s.name); printf("n Enter roll:t"); scanf("%d", &s.roll); printf("n Enter marks:t"); scanf("%f", &s.mark); printf("n Name t Roll t Markn"); printf("n...................................n"); printf("n%st%dt%f", s.name, s.roll,s.mark); getch(); }
  • 15. COPYINGAND COMPARING STRUCTURE VARIABLES 15 • Twovariables of the samestructure type canbe copied in the sameway asordinary variables. • If student1 and student2 belong tothe samestructure, then the following statements arevalid: student1=student2; student2=student1; • However, the statements suchas: student1==student2 student1!=student2 are not permitted. • If we need to compare the structure variables, we may do soby comparing members individually.
  • 16. STRUCT STUDENT { charname[20]; int roll; }; void main() { struct student student1={“ABC",4,}; struct student student2; clrscr(); student2=student1; printf("nStudent2.name=%s", student2.name); printf("nStudent2.roll=%d", student2.roll); if(strcmp(student1.name,student2.name)==0 && (student1.roll==student2.roll)) { printf("nn student1 and student2 aresame."); } getch(); } 16 Here, structure has beendeclared global i.e.outside of main() function. Now, any function can access it and create a structure variable.
  • 17. HOW STRUCTURE ELEMENTS ARE STORED? 17 • The elements of a structure are always stored in contiguous memory locations. • A structure variable reserves number of bytes equal to sum of bytes needed to each of its members. • Computer stores structures using the concept of “word boundary”. In a computer with two bytes word boundary, the structure variables are stored left aligned and consecutively one after the other (with at most one byte unoccupied in between them called slackbyte).
  • 18. HOW STRUCTURE ELEMENTS ARE STORED? 18 • When we declare structure variables, each one of them may contain slack bytes and the values stored in such slack bytes are undefined. • Due to this, even if the members of two variables are equal, their structures do not necessarily compare. • That’s why C does not permit comparison of structures.
  • 19. ARRAY OF STRUCTURE 19 • Let usconsider we have astructure as: struct student { char name[20]; int roll; char remarks; floatmarks; }; • If we want to keep record of 100 students, we have to make 100 structure variables like st1, st2,…,st100. • In this situation we can use array of structure to store the records of 100 students which is easier and efficient to handle (because loops canbe used).
  • 20. ARRAY OF STRUCTURE… 20 • Two ways to declare an array of structure:  structstudent { char name[20]; introll; char remarks; float marks; }st[100]; struct student { char name[20]; int roll; char remarks; float marks; }; struct studentst[100];
  • 21. READING VALUES for(i=0; i<5; i++) { printf("n Enter rollnumber:"); scanf("%d", &s[i].roll_no); printf("n Enter first name:"); scanf("%s", &s[i].f_name); printf("n Enter Lastname:"); scanf("%s", &s[i].l_name); }
  • 22. SORTING VALUES for(i=0; i<5;i++) { for(j=i+1; j<5; j++) { if(s[i].roll_no<s[j].roll_no) { temp =s[i].roll_no; s[i].roll_no=s[j].roll_no; s[j].roll_no=temp; } } }
  • 23. QUESTIO N 23 • Define a structure of employee having data members name, address, age and salary. Take the data for n employees in an array and find the averagesalary. • Write a program to read the name, address, and salary of 5 employees using array of structure. Display information of each employee in alphabetical order of theirname.
  • 24. ARRAY WITHIN STRUCTURE 24 • Wecanusesingle or multi dimensional arrays of type int or float. • E.g. struct student { char name[20]; introll; float marks[6]; }; struct students[100];
  • 25. ARRAY WITHIN STRUCTURE… 25 member marks[0], marks contains six marks[1], marks obtained in …, marks[5] six different • Here, the elements, indicating subjects. • These elements can be accessed using appropriate subscripts. • For example, s[25].marks[3] refers to the marks obtained in the fourth subject by the 26th student.
  • 26. for(i=0;i<n;i++) { printf("n Enter information aboutstudent%d",i+1); printf("n Name:t"); scanf(" %s", s[i].name); printf("n Class:t"); scanf("%d", &s[i]._class); printf("n Section:"); scanf(" %c", &s[i].section); printf("n Input marks of 6subjects:t"); for(j=0;j<6;j++) { scanf("%f", &temp); s[i].marks[j]=temp; } } 27 VALUES
  • 27. STRUCTURE WITHINANOTHERSTRUCTURE (NESTED STRUCTURE) 27 • Let us consider a structure personal_record to store the information of apersonas: • struct personal_record { char name[20]; intday_of_birth; intmonth_of_birth; int year_of_birth; float salary; }person;
  • 28. STRUCTURE WITHINANOTHERSTRUCTURE (NESTED STRUCTURE)… 28 • In the structure above, we cangroup all the items related to birthday together and declare them under asubstructureas: struct Date { int day_of_birth; intmonth_of_birth; int year_of_birth; }; struct personal_record { char name[20]; struct Datebirthday; float salary; }person;
  • 29. STRUCTURE WITHINANOTHERSTRUCTURE (NESTED STRUCTURE)… 29 • Here, the structure personal_record contains a member named birthday which itself is a structure with 3 members. Thisis called structure within structure. • The members contained within the inner structure can be accessedas: person.birthday.day_of_birth person.birthday.month_of_birth person.birthday. year_of_birth • The other members within the structure personal_record are accessedasusual: person.name person.salary
  • 30. 30 printf("Enter name:t"); scanf("%s", person.name); printf("nEnter day ofbirthday:t"); scanf("%d", &person.birthday.day_of_birth); printf("nEnter month of birthday:t"); scanf("%d", &person.birthday.month_of_birth); printf("nEnter year of birthday:t"); scanf("%d", &person.birthday.year_of_birth); printf("nEnter salary:t"); scanf("%f", &person.salary);
  • 31. STRUCTURE WITHINANOTHERSTRUCTURE (NESTED STRUCTURE)… 31 • Note:- More than onetype of structurescan benested…
  • 32. 32 struct date { int day; intmonth; int year; }; structname { char first_name[10]; charmiddle_name[10]; charlast_name[10]; }; structpersonal_record { float salary; struct datebirthday,deathday; struct namefull_name; };
  • 33. POINTER TO STRUCTURE 33 • Astructure type pointer variable canbe declared as: struct book { charname[20]; int pages; float price; }; structbook *bptr; • However, this declaration for a pointer to structure does not allocate any memory for a structure but allocates only for a pointer, so that to access structure’s members through pointer bptr, we must allocate the memory using malloc()function. • Now, individual structure members are accessedas: bptr->name bptr->pages bptr->price (*bptr).name (*bptr).pages (*bptr).price • Here, ->is called arrow operator and there must be apointer to the structure on the left side of thisoperator.
  • 34. 34 struct book *bptr; bptr=(struct book *)malloc(sizeof(structbook)); printf("n Entername:t"); scanf("%s", bptr->name); printf("n Enter no. ofpages:t"); scanf("%d", &bptr->pages); printf("n Enter price:t"); scanf("%f", & bptr->price=temp)
  • 35. POINTER TO STRUCTURE… 35 • Also, the address of astructure type variable canbe stored in astructure type pointer variableasfollows: struct book { char name[20]; int pages; float price; }; struct book b,*bptr; bptr=&b; • Here, the baseaddressof b is assignedtobptr pointer.
  • 36. POINTER TO STRUCTURE… 36 • Now the members of the structure book can be accessedin 3 waysas: b.name bptr->name (*bptr).name b.pages bptr->pages (*bptr).pages b.price bptr-> price (*bptr).price
  • 37. POINTER TO ARRAY OF STRUCTURE 37 • Let we haveastructure asfollows: struct book { char name[20]; intpages; float price; }; struct book b[10],*bptr; • Then the assignment statement bptr=b; assigns the address of the zeroth element of b to bptr.
  • 38. POINTER TO ARRAY OF STRUCTURE… 38 • Themembers of b[0] canbe accessedas: bptr->name bptr->pages bptr->price • Similarly members of b[1] canbe accessedas: (bptr+1)->name (bptr+1)->pages (bptr+1)->price • Thefollowing for statement canbe used to print all the values of array of structure b as: for(bptr=b;bptr<b+10;bptr++) printf(“%s %d %f”, bptr->name, bptr->pages, bptr- >price);
  • 39. PROBLE M 39 • Define a structure of employee having data members name, address, age and salary. Take data for n employee in an array dynamically and find the averagesalary. • Define a structure of student having data members name, address, marks in Clanguage, and marks in information system. Take data for n students in an array dynamically and find the total marksobtained.
  • 40. FUNCTION AND STRUCTURE 40 • Wewill consider four caseshere: – Passingthe individual membersto functions – Passingwhole structure to functions – Passingstructure pointer to functions – Passingarray of structure to functions
  • 41. 41 Passing structure member tofunctions • Structure members can be passed to functions as actual arguments in function call like ordinary variables. • Problem: Hugenumber of structuremembers • Example: Let us consider a structure employee having members name, id and salary and pass these members to afunction:
  • 42. display(emp.name,emp.id,emp.salary); VOID DISPLAY(CHAR E[],INT ID ,FLOAT SAL) { printf("nNamettIDttSalaryn); printf("%st%dt%.2f",e,id,sal); }
  • 43. PASSING WHOLE STRUCTURE TO FUNCTIONS  Whole structure canbe passedto afunction by the syntax:  function_name(structure_variable_name);  Thecalled function hasthe form:  return_typefunction_name(structtag_name structure_variable_name)  {  … … … … …;  } 45
  • 45. PASSING STRUCTURE POINTER TOFUNCTIONS • In this case, address of structure variable is passedasan actual argument to afunction. • The corresponding formal argument must be a structure type pointer variable. • Note: Any changes made to the members in the called function are directly reflected in the calling function. 47
  • 47. • Passing an array of structure type to a function is similar to passing an array of any type to afunction. • That is, the name of the array of structure is passed by the calling function which is the baseaddress of the array ofstructure. • Note: The function prototype comes after the structure definition. 49 PASSINGARRAY OF STRUCTURES TO FUNCTION
  • 48. DISPLAY(EMP); //EMP IS ARRAY NAME OF SIZE 2 void display(struct employee ee[]) { int i; printf("n Namett IDtt Salaryn"); for(i=0;i<2;i++) { printf("%stt%dtt%.2fn",ee[i].name,ee[i].id,ee[i].salary); } }
  • 49. TYPEDEF STATEMENT  U s e r Defined Data Types The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; makes the name Length a synonym (or alias) for the data type int.
  • 50. TYPEDEF(CONT D.)  T h e data “type” name Length can now be used in declarations in exactly the same way that the data type int can be used: Length a, b, len ; Length numbers[10] ;
  • 51. UNION  Union has members of different data types, but canhold data of only one member at a time.  T h e different members share the same memory location.  T h e total memory allocated to the union is equal tothe maximum size of the member.
  • 52. EXAMPLE #include <stdio.h> union marks { float percent; char grade; }; int main ( ) { union marks student1; student1.percent = 98.5; printf( "Marks are %f address is %16lun", student1.perc ent, &student1.percent); student1.grade = 'A'; printf( "Grade is %c address is %16lun",student1.grade, &student1.grade); }
  • 53. ENUMERATED DATATYPE Enumeration is a user-defined data type. It is defined using the keyword enum and the syntax is: enum tag_name {name_0, …,name_n} ;  T h e tag_name is not used directly. The names in the braces are symbolic constants that take on integer values from zero through n.
  • 54. ENUMERATED(CONT D.) As an example, thestatement: enum colors { red, yellow, green } ; creates three constants. red is assigned the value 0, yellow is assigned 1and green is assigned 2.