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

Lecture 12 Structures

The document discusses structures in C++. It defines structures as collections of variables of different data types grouped together under a single name. Structures allow storing related data together and are useful when different types of data need to be stored for the same entity. The document outlines how to declare and define structures, initialize structure variables, access members of a structure variable, and provides examples of different structure declarations.

Uploaded by

Naveed Iqbal
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

Lecture 12 Structures

The document discusses structures in C++. It defines structures as collections of variables of different data types grouped together under a single name. Structures allow storing related data together and are useful when different types of data need to be stored for the same entity. The document outlines how to declare and define structures, initialize structure variables, access members of a structure variable, and provides examples of different structure declarations.

Uploaded by

Naveed Iqbal
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

Lecture 12

Structures

1
COMP102 Prog. Fundamentals, Structures / Slide 2

Contents
 Objectives
 Structures Basics
 Initialization
 Accessing data members
 Structure to structure assignment
 Examples

2
COMP102 Prog. Fundamentals, Structures / Slide 3

Objectives
 Why do we need structures?
 Store data using simple variables; but how many variables
we can use?
 Arrays can solve this issue.
 Although, arrays greatly improved our ability to store data,
each element in an array must be of the same type.
 Sometimes, need to store data of different data types. We
use structures:
 Structure is a collection of variables of different data types under a
single name.
 Used different types of variables, can create our own type

3
COMP102 Prog. Fundamentals, Structures / Slide 4

Problems without structures

4
COMP102 Prog. Fundamentals, Structures / Slide 5

Structures
 Structures can be looked as a way to provide user-defined data types.
 A Structure is a collection of simple variables of different types.
 The data items in a structure are called the members of the structure.
 A structure in C++ is very much a class, although it may not fulfill some
properties associated with classes.
 Structure is a collection of data while class contains data & functions
 A structure type in C++ is defined by keyword struct.
 A struct is heterogeneous in that it consists of data of different data
types.
 In contrast, array is homogeneous since it can contain only data of the
same data type.

5
COMP102 Prog. Fundamentals, Structures / Slide 6

Structures
 Structures hold data that belong to each other.
 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.
6
COMP102 Prog. Fundamentals, Structures / Slide 7

Structures
 Individual components of a struct type are called members.
 Members can be of different types (simple, array or struct).
 A struct is named as a whole while individual members are
named using identifiers.
 Members defined in structure are just a blueprint for the creation
of variables.
 They don’t occupy any memory unless they are used & assigned some
value. This is against simple variable declarations.
 However, definition of structure variable reserves
enough space to hold all the members of structure ac
 cording to data types of members.
7
COMP102 Prog. Fundamentals, Structures / Slide 8

Structure Basics
 We can declare an object of type structure in same
way as we declare variables of some data type: i.e.
 Student first_student;
 The declarations of the structure are enclosed in
braces.
 A semicolon follows the closing brace, terminating the
entire structure.

struct <struct-type>{
<type> <identifier_list>; Each identifier
<type> <identifier_list>; defines a member
... of the structure.
} ;
8
COMP102 Prog. Fundamentals, Structures / Slide 9

Structure’s Function
 A structure defines
 Structure name
 Structure variable
 It assigns values to its members
 It displays the values stored.

9
COMP102 Prog. Fundamentals, Structures / Slide 10

Structure Examples
 Example:
struct StudentInfo{
int Id; The “StudentInfo”
int age;
char Gender; structure has 4 members
double CGA; of different types.
};

 Example:
struct StudentGrade{
char Name[15];
char Course[9]; The “StudentGrade”
int Lab[5]; structure has 5
int Homework[3];
int Exam[2];
members of
}; different array types.
10
COMP102 Prog. Fundamentals, Structures / Slide 11

Structure Examples
 Example:
struct BankAccount{
char Name[15]; The “BankAcount”
int AcountNo[10]; structure has simple,
double balance; array and structure
Date Birthday;
}; types as members.

 Example:
struct StudentRecord{
char Name[15]; The “StudentRecord”
int Id; structure has 4
char Dept[5];
char Gender; members.
};
11
COMP102 Prog. Fundamentals, Structures / Slide 12

Steps to create structures

12
COMP102 Prog. Fundamentals, Structures / Slide 13

Declaration
 Most efficient method of dealing with structure
variables is to define structure globally

13
COMP102 Prog. Fundamentals, Structures / Slide 14

Structure Declaration
 Declaration of a variable of struct type:
<struct-type> <identifier_list>;

 Example:
StudentRecord Student1, Student2;

Student1 and Student2 are variables of StudentRecord type.

Name Name
Student1 Student2
Id Gender Id Gender

Dept Dept

14
COMP102 Prog. Fundamentals, Structures / Slide 15

Structure Initialization-1
struct part //declare a structure
{
int modelnumber; //ID number
int partnumber; //ID number
float cost; //cost of part
};
int main()
{
part part1; //define a structure variable
part1.modelnumber = 6244; //give values to structure members
part1.partnumber = 373;
part1.cost = 217.55F;
//display structure members
cout << “Model “ << part1.modelnumber;
cout << “, part “ << part1.partnumber;
cout << “, costs $” << part1.cost << endl;
return 0; 15
}
COMP102 Prog. Fundamentals, Structures / Slide 16

2nd Way of Initialization

16
COMP102 Prog. Fundamentals, Structures / Slide 17

17
COMP102 Prog. Fundamentals, Structures / Slide 18

Accessing Data Members


 The first statement in main() is part part1;
 It defines a variable, called part1, of type structure part.
 This definition reserves space in memory for part1. How much
space?
 Enough to hold all the members of part1. In this case there will be 4 bytes for
each of the two ints (assuming a 32-bit system), and 4 bytes for the float.

18
COMP102 Prog. Fundamentals, Structures / Slide 19

Accessing Data Members


 The members of a struct type variable are accessed with the member access or dot (.) operator:
<struct-variable>.<member_name>;

 Example:
strcpy(Student1.Name, “Abc");
Student1.Id = 12345;

Student1
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M';
cout << "The student is ";
switch (Student1.gender){
case 'F': cout << "Ms. "; break;
case 'M': cout << "Mr. "; break; Name
}
cout << Student1.Name << endl;

Id Gender

Dept

Abc

12345 M

COMP
19
COMP102 Prog. Fundamentals, Structures / Slide 20

Ex. 2: struct-to-struct assignment


 The values contained in one struct type variable can be assigned to another
variable of the same struct type.

 Example: Student1
strcpy(Student1.Name,
"Chan Tai Man");
Student1.Id = 12345; Chan Tai Man
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M';
12345 M
Student2 = Student1;

COMP

Chan Tai Man

12345 M
Student2
COMP 20
COMP102 Prog. Fundamentals, Structures / Slide 21

Example: Volume of Box


#include <iostream>
using namespace std;

// Structure to represent a box


struct Box
{
double length;
double breadth;
double height;
};

// Prototype of function to calculate the volume of a box


double volume(Box& aBox); // & is used due to array

int main()
{
Box firstBox = { 80.0, 50.0, 40.0 };
COMP102 Prog. Fundamentals, Structures / Slide 22

// Calculate the volume of the box


double firstBoxVolume = volume(firstBox);
cout << endl;
cout << "Size of first Box object is "
<< firstBox.length << " by "
<< firstBox.breadth << " by "
<< firstBox.height
<< endl;
cout << "Volume of first Box object is " << firstBoxVolume
<< endl;

Box secondBox = firstBox; // Create a second Box object the


same as firstBox
// Increase the dimensions of second Box object by 10%
secondBox.length *= 1.1;
secondBox.breadth *= 1.1;
secondBox.height *= 1.1;
COMP102 Prog. Fundamentals, Structures / Slide 23

// Program 11.1 Using a Box structure……….continued-2


cout << "Size of second Box object is "
<< secondBox.length << " by "
<< secondBox.breadth << " by "
<< secondBox.height
<< endl;
cout << "Volume of second box object is " << volume(secondBox)
<< endl;

cout << "Increasing the box dimensions by 10% has increased the volume by "
<<
static_cast<long>((volume(secondBox)-firstBoxVolume)*100.0/firstBoxVolume)
<< "%"
<< endl;
return 0;
}
// Function to calculate the volume of a box
double volume(Box& aBox)
{
return aBox.length * aBox.breadth * aBox.height;
}
COMP102 Prog. Fundamentals, Structures / Slide 24

Member functions of a Structure


 In C++, it is possible to declare functions within a structure
which are also members of the structure just like the data
members.
 These functions are called member functions of the structure.
 Therefore continuing our example, in the student structure we
can declare member functions displayStudent ().
Struct Student
{
Char name[20];
Int age;
Double gpa;
// now lets have a member function
Void displayStudent( )
{
Cout << “Student Name : “ << name <<endl;
Cout << “Student Age : “ << age <<endl;
Cout << “Student GPA : “ <<gpa <<endl;
}
}
COMP102 Prog. Fundamentals, Structures / Slide 25

Member functions of a Structure


 Now we can use this member function of the structure
using the dot operator just like we were using the data
members.
 It is also possible to just declare the member function
within the structure and define the function separately
outside the structure.
 However when we provide the function definition we
must specify that the function which is being defined is
member of which structure. For this purpose we use
scope resolution operator :: .
 Therefore the function defintion would be like:
 Void student::displayStudent ( ) {………..; }
COMP102 Prog. Fundamentals, Structures / Slide 26

Nested Structures

26
COMP102 Prog. Fundamentals, Structures / Slide 27

Nested Structures

27
COMP102 Prog. Fundamentals, Structures / Slide 28

Arrays of structures
 An ordinary array: One type of data

0 1 2 … 98 99

 An array of structs: Multiple types of data in each


array element.

0 1 2 … 98 99
28
COMP102 Prog. Fundamentals, Structures / Slide 29

Arrays of structures
 We often use arrays of structures.
 Example:
StudentRecord Class[100];
strcpy(Class[98].Name, "Chan Tai Man");
Class[98].Id = 12345;
strcpy(Class[98].Dept, "COMP");
Class[98].gender = 'M';
Class[0] = Class[98]; Chan Tai Man

12345 M

COMP

...

0 1 2 … 98 99 29
COMP102 Prog. Fundamentals, Structures / Slide 30

Program Output

30
COMP102 Prog. Fundamentals, Structures / Slide 31

Remove Errors

31
COMP102 Prog. Fundamentals, Structures / Slide 32

Unions
 Union is a data type which allows you to use same block of
memory to store values of different types at different times.
 The syntax is:
union weight
{
int paisas;
double rupees;
};
 We can declare a variable of type union just like we did for
structures. Similarly data members of the union are
accessed using the dot operator.
 The major difference is that at any given point in time only
one of the data members of the union can have a value.
COMP102 Prog. Fundamentals, Structures / Slide 33

Enumeration
 An enumeration is a user-defined data type that consists of
integral constants.
 It enables you to create a new data type that has a fixed
range of possible values, and the variable can select one
value from the set of values.
 e.g., selecting only one flavor of ice cream in a shop.
 Enumerated types work when you know in advance a finite
short list of values that a data type can take on.
 An enum declaration defines the set of all names that
will be permissible values of the type.
 enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

33
COMP102 Prog. Fundamentals, Structures / Slide 34

 These permissible values are called enumerators.


 The enum type days_of_week has seven enumerators:
Sun, Mon, Tue, and so on, up to Sat.
 This feature of C++ is less crucial than structures.
 You can write perfectly good object-oriented programs in C++
without knowing anything about enumerations.

#include <iostream> day1 = Mon; //give values to


using namespace std; day2 = Thu; //variables
//specify enum type int diff = day2 - day1; //can do integer
enum days_of_week { Sun, Mon, Tue, arithmetic
Wed, Thu, Fri, Sat }; cout << “Days between = “ << diff << endl;
int main() if(day1 < day2) //can do comparisons
{ cout << “day1 comes before day2\n”;
days_of_week day1, day2; //define return 0;
variables of type days_of_week } 34
COMP102 Prog. Fundamentals, Structures / Slide 35

 Variables of an enumerated type, like day1 and


day2, can be given any of the values listed in the
enum declaration.
 In the example, we give them the values Mon and
Thu. You can’t use values that weren’t listed in the
declaration. Such statements as
 day1 = halloween;
 are illegal.

35
COMP102 Prog. Fundamentals, Structures / Slide 36

Example
 An enum variable takes only one value out of many possible
values.
#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,


Saturday };

int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Output :
Day 4 36
COMP102 Prog. Fundamentals, Structures / Slide 37

Example
 An enum variable takes only one value out of many possible
values.
#include <iostream>
using namespace std;

enum suit {
club = 0,
diamonds = 10,
hearts = 20, Output:
spades = 3
} card; Size of enum variable 4 bytes.
int main()
{
card = club;
cout << "Size of enum variable " << sizeof(card) << " bytes.";
return 0; 37
}

You might also like