0% found this document useful (0 votes)
5 views32 pages

Structures

The document provides an overview of C++ data types, focusing on structured data types such as structs, unions, and arrays. It explains how to declare and access struct members, perform operations on them, and the concept of hierarchical structures. Additionally, it discusses unions for memory conservation and includes examples of using arrays of records to manage collections of structured data.

Uploaded by

abubakar01901
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)
5 views32 pages

Structures

The document provides an overview of C++ data types, focusing on structured data types such as structs, unions, and arrays. It explains how to declare and access struct members, perform operations on them, and the concept of hierarchical structures. Additionally, it discusses unions for memory conservation and includes examples of using arrays of records to manage collections of structured data.

Uploaded by

abubakar01901
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/ 32

C++ Data Types

simple structured

integral enum floating array struct union class

char short int long bool

float double long double address

pointer reference
1
Structures
• In addition to the simple data types (int,
char, double, ...) there are composite data
types which combine more than one data
element.
• Structs
• Union
• Arrays
• Classes
Structured Data Type
A structured data type is a type in which
each value is a collection of component
items
– The entire collection has a single name
– Each component can be accessed individually
– Used to bundle together related data of various types
for convenient access under the same identifier

For example . . .

3
thisAnimal
5000

.id 2037581

.name “giant panda”

.genus “Ailuropoda”

.species “melanoluka”

.country “China”

.age 18

.weight 234.6

.health Good

4
anotherAnimal
6000

.id 5281003

.name “llama”

.genus “Lama”

.species “peruana”

.country “Peru”

.age 7

.weight 278.5

.health Excellent

5
struct AnimalType
enum HealthType { Poor, Fair, Good, Excellent };
struct AnimalType // Declares a struct data type
{ // does not allocate memory
long id;
string name;
string genus;
string species; struct members
string country;
int age;
float weight;
HealthType health;
};
// Declare variables of AnimalType
AnimalType thisAnimal;
AnimalType anotherAnimal;
66
struct type Declaration
SYNTAX
struct TypeName // Does not allocate memory
{
MemberList
};

MemberList SYNTAX

DataType MemberName;
DataType MemberName;
.
.
.
7
More About Struct Declarations
struct TypeName
{
Memebr list Optional
} VariableList;

struct StudentRec
{ struct
String firstName; {
String lastName; int firstMember;
Float gpa; float secondMember;
Int programGrade; } someVar;
Int quizeGrade;
GradeType courseGrade; //Anonyous type
}; //Such types cannot be used
// Variable declarations //in aggregate operations
StudentRec firstStudent;
StudentRec student;
struct type Declaration
The struct declaration names a type and
names the members of the struct

It does not allocate memory for any variables


of that type!

You still need to declare your struct variables

9
Accessing struct Members
Dot (period) is the member selection operator

After the struct type declaration, the various members


can be used in your program only when they are
preceded by a struct variable name and a dot

EXAMPLES
thisAnimal.weight
anotherAnimal.country

10
Operations on struct Members

The type of the member determines the allowable


operations

thisAnimal.age = 18;
thisAnimal.id = 2037581;
cin >> thisAnimal.weight;
getline (cin, thisAnimal.species);
thisAnimal.name = “giant panda”;
thisAnimal.genus[0] = toupper(thisAnimal.genus[0]);
thisAnimal.age++;

11
Aggregate Operation

An aggregation operation is an
operation on a data structure as a
whole, as opposed to an operation on
an individual component of the data
structure

12
Aggregate struct
Operations
• Operations valid on struct type variables are
▪ Assignment to another struct variable of the same
type
▪ Pass as an argument (by value or by reference)

▪ Return as value of a function


• I/O, arithmetic, and comparisons of entire
struct variables are NOT ALLOWED!

13
Aggregate struct Operations

anotherAnimal = thisAnimal; // Assignment

WriteOut(thisAnimal); // Value parameter

ChangeWeightAndAge(thisAnimal); // Reference parameter

thisAnimal = GetAnimalData(); // Function return value

14
void WriteOut( /* in */ AnimalType thisAnimal)
// Prints out values of all members of thisAnimal
// Precondition: all members of thisAnimal are assigned
// Postcondition:all members have been written out
{
cout << “ID # “ << thisAnimal.id
<< thisAnimal.name << endl;

cout << thisAnimal.genus << thisAnimal.species


<< endl;

cout << thisAnimal.country << endl;

cout << thisAnimal.age << “ years “ << endl;

cout << thisAnimal.weight << “ lbs. “ << endl;

15
Passing a struct Type by Reference

void ChangeAge(/* in out */ AnimalType& thisAnimal)

thisAnimal.age++;
}

16
AnimalType GetAnimalData ()

{
AnimalType thisAnimal;
char response;
do
{
// Have user enter members until they are correct
.

.
} while (response != ‘Y’);
return thisAnimal;
}

17
17
Hierarchical Structures
• The type of a struct member can be
another struct type

• This is called nested or hierarchical


structures

• Hierarchical structures are very useful


when there is much detailed
information in each record

For example . . . 18
struct MachineRec
Information about each machine in a shop contains:

an idNumber,

a written description,

the purchase date,

the cost,

and a history (including failure rate, number of


days down, and date of last service)

19
struct DateType
{
int month;
int day;
int year;
};
struct StatisticsType
{
float failRate;
DateType lastServiced; // DateType is a struct type
int downDays;
};
struct MachineRec
{
int idNumber;
string description;
StatisticsType history; // StatisticsType is a struct
DateType purchaseDate;
float cost;
};
MachineRec machine; 20
20
struct type variable machine

7000

5719 “DRILLING…” .02 1 25 1999 4 3 21 1995 8000.0


.month .day.year
.failrate .lastServiced .downdays .month .day .year

.idNumber .description . history .purchaseDate .cost

machine.history.lastServiced.year has value 1999


21
Unions in C++
DEFINITION
A union is a struct that holds only one of its members
at a time during program execution.

EXAMPLE
union WeightType
{
long wtInOunces;
int wtInPounds; Only one at a time
float wtInTons;
}; 22
Unions
• Just like structs but holds only one member in
memory at a time during program execution
• Purpose: It’s purpose it to conserve memory by
forcing several values to use the same memory
space one at a time
• It is quite reasonable to say that a Union is not a
data structure at all. It does not represent a
collection of values; it represents a single value
from among several potential values.
Arrays of Records
Const int MAX_STUDENTS =150;
enum GradeType {A,B,C,D,F};
struct StudentRec
{
string stuName;
float gpa;
int examScore[4];
GradeType courseGrade;
};
StudentRec gradeBook[MAX_STUDENTS];
Arrays of Records
Index 0 First record of type StudentRec

Index 1 Second record of type StudentRec


Index 2

gradeBook[2].stuName

gradeBook[2].gpa

gradeBook[2].examScore
gradeBook[2].courseGrade

gradeBook[149].stuName

gradeBook[149].gpa
Index 149 gradeBook[149].examScore

gradeBook[149].courseGrade
Arrays of Records
• gradeBook[2].courseGrade
• gradeBook[2].examScore[0]
• To print the name of each student in the class
for (count=0; count <MAX_STUDENTS;count++)
cout <<gradeBook[count].stuName <<endl;
Problem
1) Get as input the following details from the user using
struct and enumeration of any five students and
then print these details:
firstName;
lastName;
GPA;
courseGrade (A,B,C,D,F)
Grade Criteria
(A>=3; B<3 && >2.5;C<2.5&&>2;D<2&&>1.5;F<1.5;)

You might also like