Topic12 Structure
Topic12 Structure
programming I
Topic 12: Structure
1
OBJECTIVE
2
Structure
▪ Allow programmers to create a new data type which consists of
other defined data types (int, float, character, string, …)
3
Create new data type with structure
❑ Structure
▪ Problem: Information of a student (surname, name, age, sex). Suppose that we have 100
students, which data structure can be used to store these data?
▪ Inconvenient: The information are scattered from each other in many arrays.
▪ We are difficult to identify all information of a student.
4
Create new data type with structure
❑ Definition
▪ Structure a user-defined data type which allows us to combine data of different types
together. Structure helps to construct a complex data type which is more meaningful
▪ “attribute” or
▪ “member”
5
Create new data type with structure
❑ Declaration
▪ Before we can create a variable of a type structure, we need to create the structure
type first.
struct StudentInfo s; 7
Create new data type with structure
❑ How to access to element in the structure
▪ The elements of array are accessed by index while the elements of structure are accessed
by . (period)
▪ Syntax:
structureVariableName.attributeName
8
Create new data type with structure
❑ Example
Var s: student
s.name “Sok”
read(s.surname)
s.age 20
s.age s.age * 2
9
Create new data type with structure
❑ Example
12
Example: Using structure
13
Structure in C programming
❑ Using typedef to rename name of data type
myStruct ms;
14
Create new data type with structure
❑ Using typedef
S s1;
S s1;
15
Examples
16
Examples
17
Examples
18
Examples
19
An example to create
an Enumeration and
a Structure
in C programming
20
An example to create Structure
(normal and nested structure)
and using it in C programming
HOW TO:
✓ Create a structure, and nested structure
✓ Rename structure using typedef
✓ Create variable of type structure and
Initialize data.
✓ Use and access data in a structure
✓ Access data in a nested structure
21
An example to create Structure
(normal and nested structure)
and using it in C programming
HOW TO:
✓ Create a structure, and nested structure
✓ Initialize data to structure immediately
while creating
✓ Use and access data in a structure
✓ Access data in a nested structure
22
Create new data type with structure
❑ Imbrication of structure / nested structure
▪ Suppose that in the structure type of student, we need to specify the date of birth for each student
▪ Example:
How to use:
struct date
Var s: student
day, month, year: integer
end struct s.dob.year 1997
struct student
surname, name: string
dob: date
age: integer
end struct
23
Q&A
24