57
Records (structs) CS103- Computer Programming

Pf cs102 programming-10 [structs]

Embed Size (px)

Citation preview

Page 1: Pf cs102 programming-10 [structs]

Records (structs)

CS103- Computer Programming

Page 2: Pf cs102 programming-10 [structs]

2

Structures

• A Structure is a collection of related data items, possibly of different types.

• A structure type in C++ is called struct.• A struct is heterogeneous in that it can be composed of

data of different types.• In contrast, array is homogeneous since it can contain only

data of the same type.

Page 3: Pf cs102 programming-10 [structs]

3

Structures

• Structures hold data that belong together. • 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.

Page 4: Pf cs102 programming-10 [structs]

4

Structures

• Individual components of a struct type are called members (or fields).

• Members can be of different types (simple, array or struct).• A struct is named as a whole while individual members are

named using field identifiers.• Complex data structures can be formed by defining arrays

of structs.

Page 5: Pf cs102 programming-10 [structs]

5

struct basics

• Definition of a structure:struct <struct-type>{

<type> <identifier_list>;<type> <identifier_list>;...

} ;

• Example:struct Date {

int day;int month;int year;

} ;

The “Date” structure has 3 members, day, month & year.

Each identifierdefines a memberof the structure.

Page 6: Pf cs102 programming-10 [structs]

6

struct examples

• Example:struct StudentInfo{

int Id;int age;char Gender;double CGA;

};

• Example:struct StudentGrade{

char Name[15];char Course[9];int Lab[5];int Homework[3];int Exam[2];

};

The “StudentGrade” structure has 5 members ofdifferent array types.

The “StudentInfo” structure has 4 membersof different types.

Page 7: Pf cs102 programming-10 [structs]

7

struct examples• Example:

struct BankAccount{char Name[15];int AcountNo[10];double balance;Date Birthday;

};

• Example:struct StudentRecord{

char Name[15];int Id;char Dept[5];char Gender;

};

The “StudentRecord” structure has 4 members.

The “BankAcount” structure has simple, array and structuretypes as members.

Page 8: Pf cs102 programming-10 [structs]

8

struct basics

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

• Example:StudentRecord Student1, Student2;

Student1 and Student2 are variables of StudentRecord type.

Student1 Student2Name

Id Gender

Dept

Name

Id Gender

Dept

Page 9: Pf cs102 programming-10 [structs]

9

Chan Tai Man

12345 M

COMP

Ex. 1: struct basics

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

• Example:strcpy(Student1.Name, "Chan Tai Man");Student1.Id = 12345;strcpy(Student1.Dept, "COMP");Student1.gender = 'M';cout << "The student is ";switch (Student1.gender){

case 'F': cout << "Ms. "; break;case 'M': cout << "Mr. "; break;

}cout << Student1.Name << endl;

Student1

Name

Id Gender

Dept

Page 10: Pf cs102 programming-10 [structs]

Records (structs)

• struct: collection of a fixed number of components (members), accessed by name– Members may be of different types

• Syntax:

10

Page 11: Pf cs102 programming-10 [structs]

Records (structs) (cont'd.)

• A struct is a definition, not a declaration

11

Page 12: Pf cs102 programming-10 [structs]

Records (structs) (cont'd.)

12

Page 13: Pf cs102 programming-10 [structs]

Accessing struct Members

• The syntax for accessing a struct member is:

• The dot (.) is an operator, called the member access operator

13

Page 14: Pf cs102 programming-10 [structs]

Accessing struct Members (cont'd.)

• To initialize the members of newStudent:newStudent.GPA = 0.0;newStudent.firstName = "John";newStudent.lastName = "Brown";

14

Page 15: Pf cs102 programming-10 [structs]

Accessing struct Members (cont'd.)

• More examples:cin >> newStudent.firstName;cin >> newStudent.testScore >> newStudent.programmingScore;

score = (newStudent.testScore + newStudent.programmingScore) / 2;

15

Page 16: Pf cs102 programming-10 [structs]

Accessing struct Members (cont'd.)

if (score >= 90)newStudent.courseGrade = 'A';

else if (score >= 80)newStudent.courseGrade = 'B';

else if (score >= 70)newStudent.courseGrade = 'C';

else if (score >= 60)newStudent.courseGrade = 'D';

elsenewStudent.courseGrade = 'F';

16

Page 17: Pf cs102 programming-10 [structs]

17

Example Movie Struct// example about structures#include <iostream>#include <string>using namespace std;struct movies_t {string title;int year;} mine, yours;void printmovie (movies_t movie);int main ()

{string mystr;mine.title = "2001 A Space Odyssey";mine.year = 1968;cout << "Enter title: ";getline (cin,yours.title);cout << "Enter year: ";getline (cin,mystr);cin>> yours.year;cout << "My favorite movie is:\n ";

printmovie (mine);cout << "And yours is:\n ";printmovie (yours);return 0;}void printmovie (movies_t movie){cout << movie.title;cout << " (" << movie.year << ")\n";}

Page 18: Pf cs102 programming-10 [structs]

18

Example Conti…

Enter title: AlienEnter year: 1979My favorite movie is:2001 A Space Odyssey (1968)And yours is:Alien (1979)

Page 19: Pf cs102 programming-10 [structs]

Assignment

• Value of one struct variable can be assigned to another struct variable of the same type using an assignment statement

• The statement:student = newStudent;

copies the contents of newStudent into student

19

Page 20: Pf cs102 programming-10 [structs]

Assignment (cont'd.)• The assignment statement:

student = newStudent;

is equivalent to the following statements:student.firstName = newStudent.firstName;student.lastName = newStudent.lastName;student.courseGrade = newStudent.courseGrade;student.testScore = newStudent.testScore;student.programmingScore =

newStudent.programmingScore;student.GPA = newStudent.GPA; 20

Page 21: Pf cs102 programming-10 [structs]

Comparison (Relational Operators)

• Compare struct variables member-wise– No aggregate relational operations allowed

• To compare the values of student and newStudent:

21

Page 22: Pf cs102 programming-10 [structs]

Input/Output

• No aggregate input/output operations on a struct variable

• Data in a struct variable must be read one member at a time

• The contents of a struct variable must be written one member at a time

22

Page 23: Pf cs102 programming-10 [structs]

struct Variables and Functions

• A struct variable can be passed as a parameter by value or by reference

• A function can return a value of type struct23

Page 24: Pf cs102 programming-10 [structs]

Arrays versus structs

24

Page 25: Pf cs102 programming-10 [structs]

Arrays in structs

• Two key items are associated with a list: – Values (elements)– Length of the list

• Define a struct containing both items:

25

Page 26: Pf cs102 programming-10 [structs]

Arrays in structs (cont'd.)

26

Page 27: Pf cs102 programming-10 [structs]

27

Arrays in structs (cont'd.)

Page 28: Pf cs102 programming-10 [structs]

structs in Arrays

28

Page 29: Pf cs102 programming-10 [structs]

29

structs in Arrays (cont’d.)

Page 30: Pf cs102 programming-10 [structs]

30

structs in Arrays (cont’d.)

Page 31: Pf cs102 programming-10 [structs]

structs within a struct

31

versus

Page 32: Pf cs102 programming-10 [structs]

Structs, and Pointer Variables

• You can declare pointers to other data types:

– student is an object of type studentType; studentPtr is a pointer variable of type studentType

32

Page 33: Pf cs102 programming-10 [structs]

Structs, and Pointer Variables (cont'd.)

• To store address of student in studentPtr:studentPtr = &student;

• To store 3.9 in component gpa of student:(*studentPtr).gpa = 3.9;

– () used because dot operator has higher precedence than dereferencing operator

– Alternative: use member access operator arrow (->)

33

Page 34: Pf cs102 programming-10 [structs]

34

Movie Example// pointers to structures#include <iostream>#include <string>using namespace std;struct movies_t {string title;int year;};int main (){

string mystr;movies_t amovie;movies_t * pmovie;pmovie = &amovie;cout << "Enter title: ";getline (cin, pmovie->title);cout << "Enter year: ";getline (cin, mystr);

(stringstream) mystr >> pmovie->year;cout << "\nYou have entered:\n";cout << pmovie->title;cout << " (" << pmovie->year << ")\n";return 0;}

Page 35: Pf cs102 programming-10 [structs]

35

Example Output…

Enter title: Invasion of the body snatchersEnter year: 1978You have entered:Invasion of the body snatchers (1978)

Page 36: Pf cs102 programming-10 [structs]

36

Example …

pmovie->title is equivalent to (*pmovie).title

*pmovie.title is equivalent to *(pmovie.title)

Page 37: Pf cs102 programming-10 [structs]

37

Pointers & Structs

Expression What is evaluated Equivalenta.b Member b of object a

a->b Member b of object pointed by a (*a).b

*a.b Value pointed by member b of object a *(a.b)

Page 38: Pf cs102 programming-10 [structs]

38

Structs & File Handling

• A file may be read record by record.

Page 39: Pf cs102 programming-10 [structs]

39

COMPLETE EXAMPLE OF POINT

Page 40: Pf cs102 programming-10 [structs]

40

Point Struct with functions

struct Point{int x;int y;void init(){x=0;y=0;}void init(int a, int b) // Overloaded Function{x=a;y=b;}void input(){cout<<"\nEnter value of X: ";cin>>x;cout<<"\nEnter value of Y:";cin>>y;}void print(){cout<< "(" << x << "," << y <<")";}};

void main(){Point p1,p2,p3={10,6},p4; // All seem finep1.init();p1.print();p2.init(2,3);p2.print();p3.print();p4.input();p4.print();}//Output…(0,0)(2,3)(10,6)Enter value of X: 44Enter value of Y:55(44,55)

Page 41: Pf cs102 programming-10 [structs]

41

STUDENT’S HOME WORKSales Data Analysis

Page 42: Pf cs102 programming-10 [structs]

Programming Example: Sales Data Analysis

• A company has six salespeople• Every month they go on road trips to sell the company’s

product• At the end of each month, the total sales for each

salesperson, salesperson’s ID, and the month, are recorded in a file

• At the end of each year, the manager of the company asks for a report

42

Page 43: Pf cs102 programming-10 [structs]

Programming Example: Output Format----------- Annual Sales Report -------------

ID QT1 QT2 QT3 QT4 Total______________________________________________________________12345 1892.00 0.00 494.00 322.00 2708.0032214 343.00 892.00 9023.00 0.00 10258.0023422 1395.00 1901.00 0.00 0.00 3296.0057373 893.00 892.00 8834.00 0.00 10619.0035864 2882.00 1221.00 0.00 1223.00 5326.0054654 893.00 0.00 392.00 3420.00 4705.00Total 8298.00 4906.00 18743.00 4965.00

Max Sale by SalesPerson: ID = 57373, Amount = $10619.00Max Sale by Quarter: Quarter = 3, Amount = $18743.00

QT1 stands for quarter 1 (months 1 to 3), QT2 for quarter 2 (months 4 to 6), QT3 for quarter 3 (months 7 to 9), and QT4 for quarter 4 (months 10 to 12)

43

Page 44: Pf cs102 programming-10 [structs]

Programming Example: Output Format (cont'd.)

• The salespeople IDs are stored in one file; sales data are stored in another file

• The sales data is in the following form:salesPersonID month saleAmount...

• Sales data are not ordered

44

Page 45: Pf cs102 programming-10 [structs]

Programming Example: Input/Output

• Input: file containing each salesperson’s ID and a second file containing the sales data

• Output: file containing annual sales report in the above format

45

Page 46: Pf cs102 programming-10 [structs]

Programming Example: Problem Analysis

• Main components for each salesperson:– ID– Quarterly sales amount– Total annual sales amount

• Use a struct to group the components• Six people: array of size six• Program requires total sales for each

quarter– Use array of size four to store the data

46

Page 47: Pf cs102 programming-10 [structs]

Programming Example: Problem Analysis (cont'd.)

47

Page 48: Pf cs102 programming-10 [structs]

Programming Example: Problem Analysis (cont'd.)

• Read the salespeople IDs into the array salesPersonList

• Initialize the quarterly sales and total sales for each salesperson to 0

48

Page 49: Pf cs102 programming-10 [structs]

Programming Example: Problem Analysis (cont'd.)

• For each entry in the file with the sales data:– Read ID, month, sale amount for the month– Search salesPersonList to locate the component

corresponding to this salesperson– Determine the quarter corresponding to the month– Update the sales for the quarter by adding the sale amount for

the month

49

Page 50: Pf cs102 programming-10 [structs]

Programming Example: Problem Analysis (cont'd.)

• Once the sales data file is processed:– Calculate the total sale by salesperson– Calculate the total sale by quarter– Print the report

50

Page 51: Pf cs102 programming-10 [structs]

Programming Example: Algorithm Design

• Translates into the following algorithm:– Initialize the array salesPersonList – Process the sales data– Calculate the total sale by salesperson– Calculate the total sale by quarter– Print the report– Calculate and print maximum sale by salesperson– Calculate and print maximum sale by quarter

51

Page 52: Pf cs102 programming-10 [structs]

Programming Example: Main Algorithm

• Declare the variables• Prompt user to enter name of file containing the

salesperson’s ID data• Read the name of the input file• Open the input file• If input file does not exist, exit• Initialize the array salesPersonList by calling the

function initialize

52

Page 53: Pf cs102 programming-10 [structs]

Programming Example: Main Algorithm (cont'd.)

• Close input file containing salesperson’s ID• Prompt user to enter name of file containing sales data• Read the name of the input file• Open the input file• If input file does not exist, exit• Prompt user to enter name of output file• Read the name of the output file

53

Page 54: Pf cs102 programming-10 [structs]

Programming Example: Main Algorithm (cont'd.)

• Open the output file• Output data to two decimal places• Process sales data

– Call the function getData• Calculate the total sale by quarter by calling the function saleByQuarter

• Calculate the total sale by salesperson by calling the function totalSaleByPerson

54

Page 55: Pf cs102 programming-10 [structs]

Programming Example: Main Algorithm (cont'd.)

• Print the report in the tabular form; call the function printReport

• Find and print the salesperson who produces the maximum sales for the year by calling maxSaleByPerson

• Find and print the quarter producing the maximum sale for the year by calling maxSaleByQuarter

• Close files

55

Page 56: Pf cs102 programming-10 [structs]

Summary

• struct: collection of a fixed number of components

• Components can be of different types– Called members– Accessed by name

• struct is a reserved word• No memory is allocated for a struct

– Memory when variables are declared

56

Page 57: Pf cs102 programming-10 [structs]

Summary (cont'd.)

• Dot (.) operator: member access operator– Used to access members of a struct

• The only built-in operations on a struct are the assignment and member access

• Neither arithmetic nor relational operations are allowed on structs

• struct can be passed by value or reference• A function can return a value of type struct• structs can be members of other structs

57