Dfc20113 - Chapter 4 (Structure - 4.4)
Dfc20113 - Chapter 4 (Structure - 4.4)
CHAPTER 4
ARRAY, POINTER & STRUCTURE
4.4 Demonstrate the use of
structures
learning outcome
• Describe structures
• Identify the difference between structure and arrays.
• Define and declare a structure
• Assign values to a structure variable.
• Access member variables of a structure.
• Apply the coding standards and best practices for structure.
• Illustrate structures in memory.
• Solve a given problem by writing program
• Access member variables of a structure using pointer.
Introduction
Structure is a collection of related data items, possibly of different types.
A structure type in C++ is called struct.
Structure can be referred to using the same name.
The preceding structure definition does not reserve any space in
memory but the definition creates a new data types that is used to
declare variables.
Data structure
A data structure is a group of data elements grouped together under one
name. These data elements, known as members, can have different types
and different lengths.
DEFINE structure
Structures hold data that belong together.
Examples:
Student record: student id, name, major, gender, start year, …
Bank account: account number, name, currency, balance, …
Address book: name, address, telephone number, …
In database applications, structures are called records.
Difference between
structure and arrays
declare structure
Data structures are declared in C++ using the following
syntax:
struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
……..
};
declare structure
Let us assume that we want to create an account. We would need
the following information:
declare structure
Structures can
combine data of
different types
declare structure variable
Data structures variable are declared in C++ using the
following syntax:
struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
……..
}object name/structure variables;
declare structure variable
Method 1
Method 2
declare structure variable
as array
Declare a structure named Student that has ID of 10
characters, name of 40 characters, and marks of integer
type. Then, declare an array called Students with the size 25
for the structure.
assign values to a structure
variables
Given the facts about a computer, write the structure.
Manufacturer: HP
Memory: 512
Price: 2199.90
assign values to a structure
variables
Given the information structure for workers as follows:
struct infopekerja
Write programming statement to assign
{ the following workers information into
string nama; the pekerja[9] variable:
float gaji;
Nama: Ali
} pekerja [10];
Gaji: 650.00
ANSWER!
Access values in a structure
variable
Members of a structure are accessed using the member access
operators :–
the dot operator ( . ) and the arrow operator ( -> )