L34-Structure Basics
L34-Structure Basics
BASICS OF
STRUCTURES
Objectives
• Learn structure Basics
• Learn how to define a structure
• Learn how to declare variables of
structure type
• Learn how to access structure members
• Operations on structures
• Write Simple programs using structures.
Case studies
But, these basic types does not support the storage of
compound data.
Do it yourself
Case studies
Do it yourself
Applications
• A struct is heterogeneous in that it can be composed of
data of different types.
Case studies
• In contrast, array is homogeneous since it can contain
Do it yourself
only data of the same type.
Additional
Information
are called members (or fields).
Do’s
• Members can be of different types
(simple, array or struct).
Don’ts
struct tag_name
Do’s
{
Don’ts
data_type member1;
data_type member2;
Applications …
};
Case studies
Do it yourself
Case studies
• Example:
struct StudentRecord{
Do it yourself
char Name[15]; The “StudentRecord”
int Id;
char Dept[5]; structure has 4
char Gender; members.
};
CSE 101/102 Department of CSE 12/13/2018 12
Important Points Regarding
Structures
Syntax
Applications
Name Name
Case studies Student1 Id Gender Id Gender Student2
Do it yourself Dept Dept
Applications
e.g.: student s1; // s1 is a variable of type
//student structure.
Case studies
s1. rollno;
Do it yourself
s1. age;
s1. name;
CSE 101/102 Department of CSE 12/13/2018 16
Ex: Member accessing using dot operator
Syntax
• Example:
Additional
StudentRecord Student1; //Student1 is a variable of type
Information //StudentRecord
strcpy(Student1.Name, "Chan Tai Man"); Student1
Do’s
Student1.Id = 12345;
Name
Don’ts
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M'; Id Gender
Applications cout << "The student is ";
Dept
switch (Student1.gender){
Case studies case 'F': cout << "Ms. "; break;
Chan Tai Man
case 'M': cout << "Mr. "; break;
Do it yourself
} 12345 M
cout << Student1.Name << endl;
COMP
Additional
Information
Do’s
Don’ts
Applications
Case studies
Do it yourself
main()
{
struct
{
int rollno;
int age;
}s1 ={20, 21};
…
}
CSE 101/102 Department of CSE 12/13/2018 21
Structure Initialization Methods
Syntax
Do’s
main ( )
Don’ts
{
struct Student
{
Applications
int rollno;
int age;
Case studies };
Student s1={20, 21};
Do it yourself Student s2={21, 21};
}
struct Student
Do’s
{
int rollno;
Don’ts int age;
} s1={20, 21};
Applications
main ( )
Case studies {
Student s2={21, 21};
Do it yourself
…
…
}
12345 M
Additional
Information
Do’s
Don’ts
Applications
Case studies
Do it yourself
• Structure Basics
Additional
Information
• Member accessing using dot operator
Do’s
Don’ts
• Assign and compare structure variables
Applications • Simple problems using structures
Case studies
Do it yourself