0% found this document useful (0 votes)
4 views

Chapter - 7

This lecture covers the concept of structures in C++, which are user-defined data types that group related information of different types. It outlines the declaration, initialization, and operations of structures, including arrays of structures, function arguments, and pointers to structures. Additionally, it introduces linked lists as a dynamic data structure, comparing their advantages and disadvantages with arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter - 7

This lecture covers the concept of structures in C++, which are user-defined data types that group related information of different types. It outlines the declaration, initialization, and operations of structures, including arrays of structures, function arguments, and pointers to structures. Additionally, it introduces linked lists as a dynamic data structure, comparing their advantages and disadvantages with arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Lecture - 7

Structures in C++
Outline
• Intro
What is structure and why?
• Declaration of a structure
• Declaration and initialization of structure members
• Accessing structure Members
• Struct Operations
• Arrays of structures
• Structures as Function Arguments
• Pointer to structure
• Linked list
Introduction to structure
• What is structure and why?
• Structure in C++ programming language is a user defined data
type that groups logically related information of different data
types (possibly of same type) into a single type.
• It is heterogeneous in that it can be composed of data of
different types.
– In contrast, array is homogeneous; it contains only data of
the same type.
• Structure is a user-defined data type which allows us to
combine data of different types together.
• Suppose you are required to write a program to store Student
information, which will have Student’s
– name, age, department, address, father's name etc,
– which included string values, integer values etc (different
types), can you use array? Yes but it will be a daunting task
and inefficient code.
• Alternative solution: use structure.
Introduction…

• For example, it is easier to use structure than than array to


store and manipulate data on the following entities.

– Student record: studentId, name, major, gender, startYear, …


– Bank account: accountNumber, name, currency, balance, …
– Address book: name, address, telephone number, …
– Employee: Employee ID, Name, hire date, Salary, …

• In database applications, structures are called Records.


• A structure can contain any data type including array and
another structure (nested structure) as well.
Declaration of a structure

• Declaration of a structure tells the compiler name of the


structure (struct type) and type and name of structure
members.
• The following are steps to create and use structure:
1. Declare Structure
2. Initialize Members of Structure
3. Access Structure Elements
vThe first two steps are same steps for creating and using
any variable.
Declaration of a structure…
• A structure is declared by using the struct keyword followed by
structure name (also called a tag), which can be optional.
• Then, the structure members (variables) are defined with their
type and variable names inside the opening and closing braces
{ } and,
• Finally, the closing brace ends with a semicolon.
• More formally, Structures are syntactically declared with:
v Struct keyword followed by the name of the structure
(structure tag), and
v The data, contained in the structure, is defined in the curly
braces.
Declaration of …

• Syntax:

struct [structureName(tag)]
{
type memberName-1;
type memberName-2;
….
type memberName-n
};
Declaration of a structure…

• Example Notice that structure


Student structure name & variable can
be optional but not
both at the same time
struct Student struct
{ {
int id; int id;
char name[20]; OR char name[20];
char gender; char gender;
char dept[20]; char dept[20];
double cGPA; double cGPA;
}; } stud1, stud2, …stud-n;

Structure members

Structure variables…next
slides
Declaration…
• The term Student is a structure type name;
– It defines a new data type that’s a data structure of the declared form.

– By convention, the first letter of a user-selected data type name is


uppercase, as in the name Student.(previous slide)

• The Student structure consists of five data items or fields, which


are called members of the structure.

• Members can be of different types (simple, array or struct).

• The first declaration(previous slide) provides only the form( blue-


print) of student structure,
i.e., memory is not allocated yet for structure members.
Declaration…

• Memory is allocated only when structure variable(s)


is/are declared (second declaration – refer to previous
slide).
• Member names must be unique within a struct type,
i.e., same member name can be used within two or
more different struct types.
• The declaration of structure data types, like all
declarations, can be global or local.
Declaration of structure variables
How to declare
• Declaration of structure variable is just like declaration structure variable for
• of any other scalar variable. student structure
• int x; Student stud1; declaration-1 above

Data type variable Name Data type variable Name

• Student is a data type and stud1 is an instance(object) of a student


type.
• The declaration of structure data types, like all declarations, can be
global or local.
• The most efficient method of dealing with structure variables is to
define the structure globally.
• This tells “the whole world”, namely main and any functions in the
program, that a new data types exist.
• To declare a structure globally, place it BEFORE int main().
• The structure variables can then be defined locally in main, for
example. (next slide)
Declaration…

Structure variable,
An object birth of type
Date declared locally

Output:
My birth date is 12/28/86

vThis is compile time


initialization. For run-time
initialization, you can
accept values for month,
day & year from the
keyboard.
Initializing structure members

• Assigning actual data values to a structure’s members is referred to as


initialization or populating the structure.
• Syntax:
struct_variable.memberName=value;

Example:

• An alternative to initializing structure members individually (as in the


previous example) is to use array initialization rule.
• Global and local structures variables can be initialized by following the
definition with a list of initializers. For example, the definition
statement:
Date birth = {12, 28, 86};
• can be used to replace the first four statements in main() (previous
slide).
Initializing structure members…
• Structure members in C++, unlike C, can also be initialized
directly with declaration (within the structure’s body).
• Example:
Accessing structure Members

• The members of a struct type


variable are accessed with the
dot (.) operator ( also called
member access operator )
– Syntax:
struct-variable.member_name;
• Dot ( period ) is the member
selection operator.
Aggregate struct Operation

• Aggregate Operation is an operation on a data


structure as a whole.
• I/O, arithmetic, and comparisons of entire struct
variables are NOT ALLOWED!
• Valid operations on an entire struct type variable:
v assignment to another struct variable of same type
v pass to a function as argument (by value or by reference)
v return as value of a function
struct-to-struct assignment

• The values contained in one struct type variable can


be assigned to another variable of the same struct
type.
• Example:
strcpy(Student1.Name, “John Joe");
Student1.Id = 12345;
strcpy(Student1.Dept, “CSE");
Student1.gender = 'M';
Student2 = Student1;
Arrays of structures

• The real power of structures is realized when the


same structure is used for lists of data.
• For instance, in stead of storing employees’
information like IDNos in an array of integers, the
names in an array of strings, and the pay rates in an
array of double-precision numbers separately, we can
use structure to store all of these under a single name.
• This makes our program elegant and efficient.
Arrays of structures

• Declaring an array of structures is the same as declaring an


array of any other variable type.
• For example, if the data type Employee is declared as:
struct Employee
{
int id_num;
string name;
double salary;
};
, an array of 10 such structures can be defined as follows:
Employee employee_list[10];
• This definition statement constructs an array of 10 elements,
and each element is a structure of the data type Employee.
Arrays of structures…

• After an array of structures is declared, a data item is


referenced by giving the position(index) of its
structure in the array, followed by a period and the
structure member.
• Example:
employee_list[0].rate //employee_list is a variable of
Employee type
• references the rate member of the first employee
structure in the employee array.
• Arrays of structures begin indexing at 0.
Structures as Function Arguments
• Structure members can be passed to a function in the same
manner as any scalar variable. For example, given the
structure definition

• the following statement passes a copy of the structure


member emp.idNum to a function named display():
display(emp.idNum);
Structures as Function Arguments…

• When a structure is used as an argument to a function, the


entire structure is passed using the standard call-by-value
method.
– Any changes made to the contents of the structure inside the function
do not affect the structure used as an argument
• When using a structure as a parameter, remember that the
type of the argument must match the type of the parameter.
• Example(next slide)
Structures as Function Arguments…
Structures as Function Arguments…

Output:
The net pay for employee 6782 is $361.66
Structures as Function Arguments…
• An alternative to the pass-by-value function call in the above
program , in which the called function receives a copy of a
structure, is a pass by reference that passes a reference to a
structure.
• Doing so permits the called function to access and alter values
directly in the calling function’s structure variable.
• For example, referring to the previous program , the prototype
of calcNet() can be modified as the following:

double calcNet(Employee &); //in function prototype


double calcNet(Employee & temp) //in function definition
{
body;
}
Pointer to structure (structure pointer)

• A pointer variable can be created not only for built-in


types like (int, float, double etc.) but they can also be
created for user defined types like structure.
• Declaring pointer to structure:
• Syntax:
struct_type *pointer_variable_name;

Example(next slides)
Pointer to structure…Example1
Pointer to structure…Example2
Accessing structure members using pointers
• Structure members can be referenced using a pointer in two
ways:
Syntax:
1. (*pointer).memberName //dot operator
2. pointer-> memberName //arrow operator
• Either expression can be used to locate the member. For example,
the following expressions are equivalent:
(*pt).idNum can be replaced by pt->idNum
(*pt).payRate can be replaced by pt->payRate
Which one to use?
• we enclose *pointer in brackets when using (*pointer).member
since the dot (.) operator has higher precedence than the
dereference (*) operator. So, it obvious that it is easier to make
mistakes .Hence the arrow operator is preferable.
Linked List
• A linked list is a linear dynamic data structure to store data items.
• Recall that arrays is also a linear data structure that store data items in
contiguous locations.
• Unlike arrays, linked list does not necessarily store data items in contiguous
memory locations.
• A linked list is composed of elements known as "Nodes" that are divided into
two parts.
• The first component is the part where data is stored, and the second is a part
where we store the pointer to the next node.
• This type of structure is known as a "singly linked list.“
• There are different types of linked list such as singly linked list, doubly linked
list, but, in this session, only singly linked list will be introduced.
Linked List
• The following diagram shows a logical structure of a singly linked list.
head tail
100 NULL

40 200 50 300 20 400 70 NULL NULL


100 200 300 400

• As shown above, the first node of the linked list is called “head” while the last node
is called “tail”.
• The last node of the linked list will have its next pointer as null since it will not have
any memory address pointed to.
• The numbers below the nodes(100, 200, …) represent the memory address of the
respective nodes. This is just for an example; memory addresses are unsigned
hexadecimal numbers( integers).
• Notice that each preceding node contains memory address of the immediate next
node so that data elements in the linked list do not need to be stored in contiguous
locations.
• head pointer is mandatory but tail pointer is optional for singly lined list.
Linked list vs Array
• Advantages of Linked List:
• Better use of Memory
– From a memory allocation point of view, linked lists are more efficient
than arrays.
– Unlike arrays, the size for a linked list is not pre-defined, allowing the
linked list to increase or decrease in size as the program runs
(dynamically).
• Fast Insertion/Deletion Time
– inserting a new node to the beginning or end of a linked list takes
constant time (O(1)).
• Disadvantages of Linked List
• Slower Search Time
– Linked list have slower search times than arrays as random access is not
allowed. (Linked list is a sequential access data structure whereas array is
a random access data structure).
Linked list VS Array
• Disadvantages of Arrays:
• Wasted Memory
– One of the disadvantages of arrays is that memory could
be wasted since memory is allocated statically (at compile
time).

• Slow Insertion/Deletion Time


– Arrays have slow insertion and deletion times.
– To insert an element to the front or middle of the array,
the first step is to ensure that there is space in the array
for the new element, otherwise the array needs to be
resized.
Declaration of linked list
• Linked list is a user defined data type.
• In C++, linked list is declared (implemented) as a structure or as a
class.
• A self referential structure will be used to implement a linked list
and perform different operation on it, such insertion at the
beginning, middle and end of the linked list.(See next slides)
• A self referential structure is a structure which contains one or
more of its members which point to a structure variable of the
same type.
• The following is a definition of a self referential structure.

Here, next is a pointer to a node type variable (memory location in


the context of dynamic memory allocation).
Declaration of linked list

• Syntax for declaring singly liked list


struct nodeName
{
datatype variableName;
datatype variableName;
…. for storing address of
next mode
nodeName *pointervariable; //
};

§ nodeName can be any valid, descriptive name.


Operations on linked list
• Just like the other data structures, we can perform
various operations for the linked list as well. But unlike
arrays, in which we can access the element using
subscript directly, we cannot do the same random access
with a linked list.

• In order to access any node, we need to traverse the


linked list from the start and only then we can access the
desired node. Hence accessing the data randomly from
the linked list proves to be expensive.
Operations on linked list…
1.Creating(implementing liked list)
Task: To create the following node structure.
40 200 50 300 20 400 70 NULL

• These pointers can also be declared locally in main() function.


(Continued on the next slide)
Operations on linked list…
Operations on linked list…
• Task2: Insert a new data(node) at the beginning of an already
existing linked list.
• Assuming that you successfully implemented the above linked list,
here is a code to accomplish task2:

Remember that this code is part of the previous code.


Quiz
• Write a C++ program that takes list
of integers from the user (Keyboard)
and
A) Find the smallest integer.

Note: you can only use pointer to access


each element

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy