0% found this document useful (0 votes)
11 views36 pages

2_Structures

The document provides an overview of structures in programming, explaining their definition, usage, and differences from arrays. It covers topics such as declaring and initializing structure variables, assigning values, and using structures with arrays and pointers. Additionally, it discusses the relationship between structures and functions, as well as the differences between structures and classes.

Uploaded by

gajab3495
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views36 pages

2_Structures

The document provides an overview of structures in programming, explaining their definition, usage, and differences from arrays. It covers topics such as declaring and initializing structure variables, assigning values, and using structures with arrays and pointers. Additionally, it discusses the relationship between structures and functions, as well as the differences between structures and classes.

Uploaded by

gajab3495
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Structures

Department of Computer Science & IT,


The University of Lahore

1
Structure
• A Structure is a container, it can hold a bunch of
things.
– These things can be of any type.

• Structures are used to organize related data


(variables) into a nice neat package.
Introducing Structures
 A structure is a collection and is referenced with
single name.

 The data items in structure are called structure


members, elements, or fields.

 The difference between array and structure: is that


array must consists of a set of values of same data
type but on the other hand, structure may consist
of different data types.

3
Defining the Structure
• Structure definition tells how Syntax:
the structure is organized: it
struct StructName
specifies what members the {
structure will contain. DataType1 Identifier1;
DataType2 Identifier2;
.
.
.
Syntax & Example  };

Example:

struct Product
{
int ID;
string name;
float price;
};
4
Structure Definition Syntax

5
Structure members in memory
Memory is only allocated
when we create struct type
variables
4 Bytes
modelnumber

struct part
{ 4 Bytes
int partnumber
modelnumber;
int partnumber;
float cost;
}; cost 4 Bytes

6
Declaring a Structure variable
• Structure variable can be created after the definition
of a structure. The syntax of the declaration is:

StructName Identifier;

Example:
part processor;
part keyboard;

7
Another way of Declaring a Structure variable

• You can also declare struct variables during


definition of the struct. For example:
struct part
{
int
modelnumber;
int partnumber;
float cost;
} part1;

 These statements define the struct named part and


also declare part1 to be a variable of type part.
8
Examples
struct Employee struct Student
{ {
string firstName; string firstName;
string lastName; string lastName;
string address; char courseGrade;
double salary; int Score;
int deptID; double CGPA;
};
} s1, s2;

Employee e1;

9
Initializing Structure Variables
• The syntax of initializing structure is:

StructName struct_identifier = {Value1, Value2, …};

10
Structure Variable Initialization with Declaration
struct Student
{
string firstName;
string lastName;
char courseGrade;
int marks;
};

void main( )
{
Student s1= {“M”, “Umar”, ‘A’, 94} ;
}

Note: Values should be written in the same sequence in which


they are specified in structure definition. 11
Assigning Values to Structure Variables
• After creating structure variable, values to structure
members can be assigned using dot (.) operator

• The syntax is as follows:

student s1;

s1.firstName = “ABC”;
s1.lastName = “XYZ”;
s1.courseGrade = ‘A’;
s1.marks = 93;
12
Assigning Values to Structure Variables
• After creating structure variable, values to structure
members can be assigned using cin

• Output to screen using cout

student s1;

cin>>s1.firstName;
cin>>s1.lastName;
cin>>s1.courseGrade;
cin>>s1.marks ;
13
Assigning one Structure Variable to another
• A structure variable can be assigned to another
structure variable only if both are of same type

• A structure variable can be initialized by assigning


another structure variable to it by using the
assignment operator as follows:

Example:
studentType Student1 = {“Amir”, “Ali”, ‘A’, 98} ;
studentType student2 = Student1;

14
Array of Structures
An array of structure is a type of array in which each
element contains a complete structure.

struct Book
{
int ID;
int Pages;
float Price;
};
Book Library[100]; // declaration of array of structures

ID
Library[0]
Pages Price ID
Library[1]
Pages Price
… ID
Library[99]
Pages Price
15
Initialization of Array of Structures
struct Book
{
int ID;
int Pages;
float Price;
};
Book b[3]; // declaration of array of structures

• Initializing can be at the time of declaration


Book b[3] = {{1,275,70},{2,600,90},{3,786,100}};

• Or can be assigned values using cin:


cin>>b[0].ID ;
cin>>b[0].Pages;
cin>>b[0].Price; 16
Partial Initialization of Array of Structures

17
Array as Member of Structures
• A structure may also contain arrays as members.

struct Student
{
int RollNo;
float Marks[3];
};

• Initialization can be done at time of declaration:

Student S = {1, {70.0, 90.0, 97.0} };


18
Array as Member of Structures
• Or it can be assigned values later in the program:
Student S;
S.RollNo = 1;
S.Marks[0] = 70.0;
S.Marks[1] = 90.0;
S.Marks[2] = 97.0;

• Or user can use cin to get input directly:


cin>>S.RollNo;
cin>>S.Marks[0];
cin>>S.Marks[1];
cin>>S.Marks[2];
19
Nested Structure
• A structure can be a member of another structure:
called nesting of structure.
struct A
{
int x;
double y;
};

struct B
{ record
char ch; v1
A v1; ch x y
};

B record; 20
Initializing/Assigning to Nested Structure
struct A{ void main() // Input
int x; {
float y; B record;
}; cin>>record.ch;
cin>>record.v2.x;
struct B{ cin>>record.v2.y;
char ch; }
A v2;
}; void main() // Assignment
{
B record;
void main() // Initialization record.ch = ‘S’;
{ record.v2.x = 100;
B record = {‘S’, {100, 3.6} }; record.v2.y = 3.6;
} }
21
Accessing Structures with Pointers
• Pointer variables can be used to point to structure
type variables too.
• The pointer variable should be of same type, for
example: structure type

struct Rectangle {
int width;
int height;
};

void main( )
{
Rectangle rect1={22,33};
Rectangle* rect1Ptr = &rect1; 22
}
Accessing Structures with Pointers
• How to access the structure members (using
pointer)?
– Use dereferencing operator (*) with dot (.) operator

struct Rectangle {
int width;
int height;
};

void main( )
{
Rectangle rect1={22,33};
Rectangle* rectPtr = &rect1;
cout<< (*rectPrt).width<<(*rectPrt).height; 23
}
Accessing Structures with Pointers
• Is there some easier way also?
– Use arrow operator ( -> )

struct Rectangle {
int width;
int height;
};

void main( )
{
Rectangle rect1={22,33};
Rectangle* rectPtr = &rect1;
cout<< rectPrt->width<<rectPrt->height;
24
}
Anonymous Structure
• Structures can be anonymous:
• Anonymous structure definition must have a structure
type variable.

25
Other stuff you can do with a struct
• You can also associate functions with a structure
(called member functions)

• A C++ class is very similar to a structure, we will


focus on classes.
– can have (data) members
– can have member functions.
– can also hide some of the members (functions and
data).
Quick Example
struct StudentRecord {
char *name; // student name
int marks[5]; // test grades
double ave; // final average

void print_ave( ) {
cout << "Name: " << name << endl;
cout << "Average: " << ave << endl;
}
};
Using the member function
StudentRecord stu;

… // set values in the structure

stu.print_ave( );
Structures and Functions
• Structures can be passed in a function:
1. Pass-by-value
2. Pass-by-reference
3. Pass-by-reference (using pointers)

29
Structures and Functions – By Value

30
31
Structures and Functions – By Value
• Problem: copy of a large structure takes time and a lot
of memory

• Solution: Pass-by reference (conserves the memory)


– Problem: Function can update/change original values…
– Solution: constant reference

32
Structures and Functions
• Structures can be returned by a function

33
Structures Vs. Classes
• Members in Structures are default public
• Members in Classes are default private

• Traditionally, structures are used in 'C' language for


holding records consisting of many data values

• Classes are meant to describe objects having both


private state/data and public member functions

34
Practice Question 1
• Define a structure called “car”. The member elements
of the car structure are:
• string Model;
• int Year;
• float Price

Create an array of 30 cars. Get input for all 30 cars


from the user. Then the program should display
complete information (Model, Year, Price) of those
cars only which are above 500000 in price.

35
Practice Question 2
• Write a program that implements the following using C++
struct. The program should finally displays the values stored
in a phone directory (for 10 people)

PhoneDirectory

Name PhoneNo Address

City Country

36

You might also like