C++ Derived Data Types

Post on 27-Nov-2014

1.052 views 5 download

Transcript of C++ Derived Data Types

1

BITG 1113:BITG 1113: DERIVED DATA TYPES DERIVED DATA TYPES

(ENUMERATED DATA TYPE AND (ENUMERATED DATA TYPE AND STRUCTURE)STRUCTURE)

LECTURE 11

OBJECTIVES:

To understand the concept of enum & structure

To understand the differences between array

and structure

To understand how to use structure in program

To understand structure containing array and

array of structure

2

3

4

• An enumerated data type is a programmer-defined data type.

•It consists of values known as enumerators, which represent

integer constants.

•Use symbolic names rather than number – makes program much

more readable.

Enumerated Data Type

5

Enumerated Data Type• Format of enumerated tag :

•Example: An enumerated data type for the working days in a week is

shown below, followed by a variable definition.

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };

Day workDay;

Note that :

The enumerators which are listed inside the braces, are not strings.

They represent the values that belong to the Day data type.

workDay is a variable of the Day type.

enum Tag { enumerators };

Tag variable_identifier;

6

• We may assign any of the enumerators MONDAY, TUESDAY,

WEDNESDAY, THURSDAY, or FRIDAY to a variable of the Day type.

Example:

workDay = WEDNESDAY;

•So, what is an enumerator?

It as an integer named constant. Internally, the compiler assigns integer

values to the enumerators, beginning at 0.

• When you don’t tell C++ what values you want to use, it simply starts at

0 and then equates each enumerated constant to the next higher integral

number.

Enumerated Data Type

7

Enumerated Data Type

• Therefore, MONDAY equates to 0, TUESDAY equates to 1, and so

forth, until we get to FRIDAY, which equates to 4.

•Using the Day declaration, the following code...

cout << MONDAY << " "

<< WEDNESDAY << " "

<< FRIDAY << endl;

...will produce this output:

0 2 4

8

•To equate each working days to its normal value, such as the value 1

for MONDAY, its done with assigning operator as shown below:

enum Day {MONDAY=1,TUESDAY=2, WEDNESDAY=3, THURSDAY=4,

FRIDAY=5};

• Here’s Day coded in the shorter way.

enum Day {MONDAY=1,TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};

Enumerated Data Type

9

• C++ allows you to assign the same integer to multiple enumeration

constants in the same definition. For example, in the enumerated Day

below, we have assigned the same number to WEDNESDAY and

THURSDAY:

enum Day {MONDAY,TUESDAY, WEDNESDAY, THURSDAY=2, FRIDAY};

Enumerated Data Type

10

• You can assign an enumerator value to an int variable.

• However we cannot assign an integer value to an enum variable, unless

we cast it.

• Example :

enum Day {MONDAY,TUESDAY, WEDNESDAY,THURSDAY, FRIDAY};Day day1, day2; // Define two Day variables.int x; // Define an int variable.

day1 = MONDAY; // OK. So day1 is 0.

day2 = 1; // ERROR. Cannot store int value // in an enum variable

day2 = static_cast<Day>(1); // OK. The solution to the // error above.

x = FRIDAY; //OK. So x is 4.

Enumerated Data Type

11

Program 11-1

PROGRAM 11-1 (CONTINUED)

12

Program 11-1 shows enumerators used to control a loop:

int index;

// Get the sales for each day.

for (index = MONDAY; index <= FRIDAY; index++){ cout << "Enter the sales for day " << index << ": "; cin >> sales[index];}

13

Remember, though, we cannot use the ++ operator on an enum variable. So, the following loop will NOT work

14

Day workDay; // Define a Day variable

// ERROR!!! This code will NOT work.for (workDay = MONDAY; workDay <= FRIDAY; workDay++){ cout << "Enter the sales for day " << workDay << ": "; cin >> sales[workDay];}

You must rewrite the loop’s update expression using a cast instead of ++:

15

Day workDay; // Define a Day variable

for (workDay = MONDAY; workDay <= FRIDAY; workDay = static_cast<Day>(workDay + 1)){ cout << "Enter the sales for day " << workDay << ": "; cin >> sales[workDay];}

16

• Structure – is a collection of related elements, possibly of different

types, having a single name.

• Each element in a structure is called a field.

• A field is the smallest element of named data that has meaning.

• The different between an array and a structure is that all elements

in an array must be of the same type, while the elements in a

structure can be of the same or different types.

Structure

17

5 7

1234 F A T I MA /0H 3.7

Structure

•The first example fraction, has two fields, both of which are

integers. The second example, student, has three fields, an

integer number, an array and a floating point number.

18

• To declare a structure type, use the keyword struct followed

by the name of the type and its field list.

General Format: struct <structName>{

type1 field1;type2 field2;. . .

};

• To define its variables, use the structure tag (name) as the

variable’s type.

Structure Declaration and Definition

19

structure tag

structure members

studentID

name

yearInSchool

gpa

bill

Structure Declaration and Definition

Example :

20

• A structure can be initialized.

• The rules for structure initialization are similar to the rules for array

initialization:

(1) the initializers are enclosed in braces and separated by commas;

(2) the initializers must match their corresponding types in the

structure declaration;

(3) if use a nested structure, the nested initializers must be enclosed in

their own set of braces.

Structure Initialization

21

Example :

Structure Initialization

struct SAMPLE{

int x;int y;float t;char u;

};SAMPLE sam1 = { 2, 5, 3.2, ’A’ };

SAMPLE sam2 = { 7, 3 };

sam2

sam1

22

• We can read data into and write data from structure members just as we can from individual variables.

• For example the value for the field of the sample structure can be read from the keyboard and placed in sam2 using the input statement below.

cin >> sam2.x >>sam2.y >>sam2.t >>sam2.u;

Referencing Individual Field

R

23

• The structure is an entity that can be treated as a whole.

• However, only one operation, assignment is allowed on the structure

itself. In other words, a structure can only be copied to another structure of

the same type using the assignment operator.

• Example :

Structure Operation

struct STUDDATA{int id;char name[20];float gradePoint;};

void main( ){ STUDDATA studBITG1113; cout << "Please enter your id"; cin >> studBITG1113.id; cout << "\nPlease enter your name"; cin.getline(studBITG1113.name,19); cout << "\nPlease enter your gradePoint"; cin >> studBITG1113.gradePoint;

cout << "\nYour id is :"<<studBITG1113.id; cout << "\nYour name is :"<<studBITG1113.name; cout << "\nYour grade point is :"<<studBITG1113.gradePoint;

if(studBITG1113.gradePoint > 3.5)

cout<<"Excellent!"}

24

Program 11-2 : A struct to keep a set

of data

25

• We can have structures as members of a structures.

•When a structure includes another structure, it is a nested structure.

• For example, we can have a structure called STAMP that stores the date and the time.

•The DATE is in turn a structure that stores the month, day and year.

•The TIME is also structure, one that stores the hour, minute and second.

Nested Structure

26

•This structure design as :

struct DATE{ int month; int day; int year;};struct TIME{ int hour; int min; int sec;}; struct STAMP{ DATE date; TIME time;};

STAMP stamp;

27

• It is possible to nest the same structure type more than once in a declaration.Example :

struct JOB

{

STAMP startTime;

STAMP endTime;

};

JOB job;

28

• When access a nested structure, we must include each level from the highest (stamp) to the component being referenced.

Referencing Nested Structure

29

• Structures can have one or more arrays as members.

Structure Containing Array

/*Global declarations */struct PUPIL{char name[26];int midterm[3];int final;};

PUPIL student;

struct STUDDATA{char name[20];float test[3];float ass[5];float quiz[2];float final;float total;float project;};

void main( ){ STUDDATA studBITG1113; float totTest =0, totAss = 0, totQuiz=0; cout << "\nPlease enter your name : "; cin.getline(studBITG1113.name,19); for( int i = 0; i < 3; i++ ){ cout << "\nPlease enter the score for test : "<< i+1; cin >> studBITG1113.test[i];

totTest += studBITG1113.test[i]; }

30

Program 11-3 : A struct with array

members

for(i=0; i<5; i++){ cout << "\nPlease enter the score for assignment"<<i+1<<" : "; cin >> studBITG1113.ass[i];

totAss += studBITG1113.ass[i]; }

for(i=0; i<2; i++){ cout << "\nPlease enter the score for quiz"<<i+1 <<" : "; cin >> studBITG1113.quiz[i];

totQuiz += studBITG1113.quiz[i]; }

cout << "\nPlease enter the score for final : "; cin >> studBITG1113.final;

cout << "\nPlease enter the score for project : "; cin >> studBITG1113.project;

studBITG1113.total = totTest + totAss + totQuiz + studBITG1113.final + studBITG1113.project;

cout << "\nYour score for this subject is : ” << studBITG1113.total;}

31

32

Output :

33

• As a programmer, you will encounter many situations that require you to create an array of structures.

• By putting the data in an array, we can quickly and easily work with the data.

• Example array of structures might look.

Array of Structure

34

struct PELAJAR{int id;char name[31];float project_mark;int test_mark;int final_mark;char gred;};

PELAJAR rekod_pelajar[3];

Example : Array of Structure

struct pelajar rekod_pelajar[] = {{1342, "Zulaiha Ismail", 10.2, 10, 20, ‘F’},{1343, "Aina Ahmad", 51.4, 60, 60, ‘C’},{1344, "Maria Musa", 90.0, 99, 99, ‘A’}};

OR with initialization :

35

To print the elements in rekod_pelajar : for(i=0; i<3;i++){ cout << rekod_pelajar[i].id <<endl;

cout << rekod_pelajar[i].name <<endl;cout << rekod_pelajar[i].project_mark <<endl;cout << rekod_pelajar[i].test_mark <<endl;cout << rekod_pelajar[i].final_mark <<endl;cout << rekod_pelajar[i].gred <<endl;

}

Example : Array of Structure

struct STUDDATA{

char name[20]; float test[3];float ass[5];float quiz[2];float final;float total;float project;

};

void main( ){ STUDDATA studBITG1113[50]; float totTest = 0, totAss = 0, totQuiz = 0;

for( int i = 0; i < 50< i++ ){ cout << "\nPlease enter your name : "; cin.getline(studBITG1113[i].name,19); for( i=0; i<3;i++ ){ cout << "\nPlease enter the score for test : "<<i+1; cin >> studBITG1113[i].test[i];

totTest += studBITG1113[i].test[i]; }

36

Program 11-4 : Array with struct as

its elements

for( i = 0; i < 5; i++ ){ cout << "\nPlease enter the score for assignment"<<i+1<<" : "; cin >> studBITG1113[i].ass[i];

totAss += studBITG1113[i].ass[i]; }

for( i = 0; i < 2; i++ ){ cout << "\nPlease enter the score for quiz"<<i+1 <<" : "; cin >> studBITG1113[i].quiz[i];

totQuiz += studBITG1113[i].quiz[i]; }

cout << "\nPlease enter the score for final : "; cin >> studBITG1113[i].final;

cout << "\nPlease enter the score for final : "; cin >> studBITG1113[i].project;

studBITG1113[i].total = totTest + totAss + totQuiz + studBITG1113[i].final + studBITG1113[i].project;

cout <<"\nYour score for this subject is : ” <<studBITG1113[i].total; }} 37