Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 10: Records ( struct s)

Similar presentations


Presentation on theme: "C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 10: Records ( struct s)"— Presentation transcript:

1 C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 10: Records ( struct s)

2 C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will: Learn about records ( struct s) Examine various operations on a struct Explore ways to manipulate data using a struct Learn about the relationship between a struct and functions Discover how arrays are used in a struct Learn how to create an array of struct items

3 C++ Programming: Program Design Including Data Structures, Fourth Edition3 Records ( struct s) struct : collection of a fixed number of components (members), accessed by name −Members may be of different types Syntax:

4 C++ Programming: Program Design Including Data Structures, Fourth Edition4 Records ( struct s) (continued) A struct is a definition, not a declaration

5 C++ Programming: Program Design Including Data Structures, Fourth Edition5 Records ( struct s) (continued)

6 C++ Programming: Program Design Including Data Structures, Fourth Edition6 Accessing struct Members The syntax for accessing a struct member is: The dot (. ) is an operator, called the member access operator

7 C++ Programming: Program Design Including Data Structures, Fourth Edition7 Accessing struct Members (continued) To initialize the members of newStudent : newStudent.GPA = 0.0; newStudent.firstName = "John"; newStudent.lastName = "Brown";

8 C++ Programming: Program Design Including Data Structures, Fourth Edition8 Accessing struct Members (continued) More examples: cin >> newStudent.firstName; cin >> newStudent.testScore >> newStudent.programmingScore; score = (newStudent.testScore + newStudent.programmingScore) / 2; 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'; else newStudent.courseGrade = 'F';

9 C++ Programming: Program Design Including Data Structures, Fourth Edition9 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

10 C++ Programming: Program Design Including Data Structures, Fourth Edition10 Assignment (continued) 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;

11 C++ Programming: Program Design Including Data Structures, Fourth Edition11 Comparison (Relational Operators) Compare struct variables member-wise −No aggregate relational operations allowed To compare the values of student and newStudent :

12 C++ Programming: Program Design Including Data Structures, Fourth Edition12 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

13 C++ Programming: Program Design Including Data Structures, Fourth Edition13 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 struct

14 C++ Programming: Program Design Including Data Structures, Fourth Edition14 Arrays versus struct s

15 C++ Programming: Program Design Including Data Structures, Fourth Edition15 Arrays in struct s Two key items are associated with a list: −Values (elements) −Length of the list Define a struct containing both items:

16 C++ Programming: Program Design Including Data Structures, Fourth Edition16 Arrays in struct s (continued)

17

18 C++ Programming: Program Design Including Data Structures, Fourth Edition18 struct s in Arrays

19

20

21 C++ Programming: Program Design Including Data Structures, Fourth Edition21 struct s within a struct versus

22

23 C++ Programming: Program Design Including Data Structures, Fourth Edition23 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

24 C++ Programming: Program Design Including Data Structures, Fourth Edition24 Programming Example: Output Format ----------- Annual Sales Report ------------- ID QT1 QT2 QT3 QT4 Total ______________________________________________________________ 12345 1892.00 0.00 494.00 322.00 2708.00 32214 343.00 892.00 9023.00 0.00 10258.00 23422 1395.00 1901.00 0.00 0.00 3296.00 57373 893.00 892.00 8834.00 0.00 10619.00 35864 2882.00 1221.00 0.00 1223.00 5326.00 54654 893.00 0.00 392.00 3420.00 4705.00 Total 8298.00 4906.00 18743.00 4965.00 Max Sale by SalesPerson: ID = 57373, Amount = $10619.00 Max 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)

25 C++ Programming: Program Design Including Data Structures, Fourth Edition25 Programming Example: Output Format (continued) 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

26 C++ Programming: Program Design Including Data Structures, Fourth Edition26 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

27 C++ Programming: Program Design Including Data Structures, Fourth Edition27 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

28 C++ Programming: Program Design Including Data Structures, Fourth Edition28 Programming Example: Problem Analysis (continued)

29 C++ Programming: Program Design Including Data Structures, Fourth Edition29 Programming Example: Problem Analysis (continued) Read the salespeople IDs into the array salesPersonList Initialize the quarterly sales and total sales for each salesperson to 0

30 C++ Programming: Program Design Including Data Structures, Fourth Edition30 Programming Example: Problem Analysis (continued) 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

31 C++ Programming: Program Design Including Data Structures, Fourth Edition31 Programming Example: Problem Analysis (continued) Once the sales data file is processed: −Calculate the total sale by salesperson −Calculate the total sale by quarter −Print the report

32 C++ Programming: Program Design Including Data Structures, Fourth Edition32 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

33 C++ Programming: Program Design Including Data Structures, Fourth Edition33 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

34 C++ Programming: Program Design Including Data Structures, Fourth Edition34 Programming Example: Main Algorithm (continued) 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

35 C++ Programming: Program Design Including Data Structures, Fourth Edition35 Programming Example: Main Algorithm (continued) 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

36 C++ Programming: Program Design Including Data Structures, Fourth Edition36 Programming Example: Main Algorithm (continued) 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

37 C++ Programming: Program Design Including Data Structures, Fourth Edition37 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

38 C++ Programming: Program Design Including Data Structures, Fourth Edition38 Summary (continued) 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 struct s struct can be passed by value or reference A function can return a value of type struct struct s can be members of other struct s

39 Starting Out with C++: Early Objects 5/e© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 7 Structured Data and Classes

40 Chapter 8 Starting Out with C++: Early Objects 5/e slide 40 © 2006 Pearson Education. All Rights Reserved Topics 7.1 Combining Data into Structures 7.2 Accessing Structure Members 7.3 Initializing a Structure 7.4 Nested Structures 7.5 Structures as Function Arguments 7.6 Returning a Structure from a Function 7.7 Unions 7.8 Abstract Data Types 7.9 Object-Oriented Programming

41 Chapter 8 Starting Out with C++: Early Objects 5/e slide 41 © 2006 Pearson Education. All Rights Reserved Topics (Continued) 7.10 Introduction to Classes 7.11 Introduction to Objects 7.12 Defining Member Functions 7.13 Design Considerations 7.14 Using a Constructor with a Class 7.15 Overloading Constructors 7.16 Destructors 7.17 Input Validation Objects 7.18 Using Private Member Functions

42 Chapter 8 Starting Out with C++: Early Objects 5/e slide 42 © 2006 Pearson Education. All Rights Reserved 7.1 Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure Declaration Format: struct structure name { type1 field1; type2 field2; … typen fieldn; };

43 Chapter 8 Starting Out with C++: Early Objects 5/e slide 43 © 2006 Pearson Education. All Rights Reserved Example struct Declaration struct Student { int studentID; string name; short year; double gpa; } ; structure tag structure members Notice the required ;

44 Chapter 8 Starting Out with C++: Early Objects 5/e slide 44 © 2006 Pearson Education. All Rights Reserved struct Declaration Notes struct names commonly begin with an uppercase letter Multiple fields of same type can be in a comma-separated list string name, address;

45 Chapter 8 Starting Out with C++: Early Objects 5/e slide 45 © 2006 Pearson Education. All Rights Reserved Defining Structure Variables struct declaration does not allocate memory or create variables To define variables, use structure tag as type name Student s1; studentID name year gpa s1

46 Chapter 8 Starting Out with C++: Early Objects 5/e slide 46 © 2006 Pearson Education. All Rights Reserved 7.2 Accessing Structure Members Use the dot (.) operator to refer to members of struct variables getline(cin, s1.name); cin >> s1.studentID; s1.gpa = 3.75; Member variables can be used in any manner appropriate for their data type

47 Chapter 8 Starting Out with C++: Early Objects 5/e slide 47 © 2006 Pearson Education. All Rights Reserved #include using namespace std; #define SIZE 8 struct student { int id; string name; double grade; };

48 Chapter 8 Starting Out with C++: Early Objects 5/e slide 48 © 2006 Pearson Education. All Rights Reserved void initializae_class(struct student aclass[], int size){ aclass[0].id=1; aclass[0].name="Jack"; aclass[0].grade=62.3; aclass[1].id=2; aclass[1].name="Tome"; aclass[1].grade=92.7; aclass[2].id=3; aclass[2].name="Zak"; aclass[2].grade=53.5; …… }

49 Chapter 8 Starting Out with C++: Early Objects 5/e slide 49 © 2006 Pearson Education. All Rights Reserved void rank(struct aclass[ ], int size){ //Use bubble sorting. }

50 Chapter 8 Starting Out with C++: Early Objects 5/e slide 50 © 2006 Pearson Education. All Rights Reserved void print_class(struct student aclass[], int size){ int i; for (i=0; i<size; i++){ cout cout<<"\n Name: "<<aclass[i].name<<", Id: "<<aclass[i].id <<", Grade: "<<aclass[i].grade; } int main(){ struct student ourclass[SIZE]; initializae_class(ourclass, SIZE); print_class(ourclass, SIZE); //call rank() //print out students again. return 0; }

51 Chapter 8 Starting Out with C++: Early Objects 5/e slide 51 © 2006 Pearson Education. All Rights Reserved Displaying struct Members To display the contents of a struct variable, you must display each field separately, using the dot operator Wrong: cout << s1; // won’t work! Correct: cout << s1.studentID << endl; cout << s1.name << endl; cout << s1.year << endl; cout << s1.gpa;

52 Chapter 8 Starting Out with C++: Early Objects 5/e slide 52 © 2006 Pearson Education. All Rights Reserved #include using namespace std; struct PayRoll { int empNumber; // Employee number string name; // Employee name double hours, // Hours worked payRate, // Hourly pay rate grossPay; // Gross pay };

53 Chapter 8 Starting Out with C++: Early Objects 5/e slide 53 © 2006 Pearson Education. All Rights Reserved int main(){ PayRoll employee; //Get the employee data cout << "Enter the employee's number: "; cin >> employee.empNumber; cout << "Enter the employee's name: "; cin.ignore(); // Skip the '\n' character left in the buffer getline(cin, employee.name); cout << "How many hours did the employee work? "; cin >> employee.hours; cout << "What is the employee's hourly pay rate? "; cin >> employee.payRate;

54 Chapter 8 Starting Out with C++: Early Objects 5/e slide 54 © 2006 Pearson Education. All Rights Reserved // Calculate gross pay employee.grossPay = employee.hours * employee.payRate; // Display results cout << "\nHere is the employee's payroll data:\n"; cout << "Name: " << employee.name << endl; cout << "Number: " << employee.empNumber << endl; cout << "Hours worked: " << employee.hours << endl; cout << "Hourly pay rate: " << employee.payRate << endl; cout << fixed << showpoint << setprecision(2); cout << "Gross pay: $" << employee.grossPay << endl; return 0; }

55 Chapter 8 Starting Out with C++: Early Objects 5/e slide 55 © 2006 Pearson Education. All Rights Reserved 7.3 Initializing a Structure Cannot initialize members in the structure declaration, because no memory has been allocated yet struct Student // Illegal { // initialization int studentID = 1145; string name = "Alex"; short year = 1; float gpa = 2.95; };

56 Chapter 8 Starting Out with C++: Early Objects 5/e slide 56 © 2006 Pearson Education. All Rights Reserved Initializing a Structure (continued) Structure members are initialized at the time a structure variable is created Can initialize a structure variable’s members with either −an initialization list −a constructor

57 Chapter 8 Starting Out with C++: Early Objects 5/e slide 57 © 2006 Pearson Education. All Rights Reserved Using an Initialization List An initialization list is an ordered set of values, separated by commas and contained in { }, that provides initial values for a set of data members {12, 6, 3} // initialization list // with 3 values

58 Chapter 8 Starting Out with C++: Early Objects 5/e slide 58 © 2006 Pearson Education. All Rights Reserved More on Initialization Lists Order of list elements matters: First value initializes first data member, second value initializes second data member, etc. Elements of an initialization list can be constants, variables, or expressions {12, W, L/W + 1} // initialization list // with 3 items

59 Chapter 8 Starting Out with C++: Early Objects 5/e slide 59 © 2006 Pearson Education. All Rights Reserved Initialization List Example Structure Declaration Structure Variable struct Dimensions { int length, width, height; }; Dimensions box = {12,6,3}; box length12 width 6 height3

60 Chapter 8 Starting Out with C++: Early Objects 5/e slide 60 © 2006 Pearson Education. All Rights Reserved Partial Initialization Can initialize just some members, but cannot skip over members Dimensions box1 = {12,6}; //OK Dimensions box2 = {12,,3}; //illegal

61 Chapter 8 Starting Out with C++: Early Objects 5/e slide 61 © 2006 Pearson Education. All Rights Reserved Problems with Initialization List Can’t omit a value for a member without omitting values for all following members Does not work on most modern compilers if the structure contains any string objects −Will, however, work with C-string members

62 Chapter 8 Starting Out with C++: Early Objects 5/e slide 62 © 2006 Pearson Education. All Rights Reserved Using a Constructor to Initialize Structure Members A constructor is a special function that can be a member of a structure It is normally written inside the struct declaration Its purpose is to initialize the structure’s data members

63 Chapter 8 Starting Out with C++: Early Objects 5/e slide 63 © 2006 Pearson Education. All Rights Reserved A Structure with a Constructor struct Dimensions { int length, width, height; // Constructor Dimensions(int L, int W, int H) {length = L; width = W; height = H;} };

64 Chapter 8 Starting Out with C++: Early Objects 5/e slide 64 © 2006 Pearson Education. All Rights Reserved Using a Constructor (continued) Unlike most functions, a constructor is not called; instead, it is automatically invoked when a structure variable is created The constructor name must be the same as the structure name (i.e. the struct tag) The constructor must have no return type

65 Chapter 8 Starting Out with C++: Early Objects 5/e slide 65 © 2006 Pearson Education. All Rights Reserved Passing Arguments to a Constructor Create a structure variable and follow its name with an argument list Example: Dimensions box3(12, 6, 3);

66 Chapter 8 Starting Out with C++: Early Objects 5/e slide 66 © 2006 Pearson Education. All Rights Reserved Default Arguments A constructor may be written to have default arguments struct Dimensions { int length, width, height; // Constructor Dimensions(int L=1, int W=1, int H=1) {length = L; width = W; height = H;} };

67 Chapter 8 Starting Out with C++: Early Objects 5/e slide 67 © 2006 Pearson Education. All Rights Reserved Examples //Create a box with all dimensions given Dimensions box4(12, 6, 3); //Create a box using default value 1 for //height Dimensions box5(12, 6); //Create a box using all default values Dimensions box6; Omit () when no arguments are used

68 Chapter 8 Starting Out with C++: Early Objects 5/e slide 68 © 2006 Pearson Education. All Rights Reserved 7.5 Structures as Function Arguments May pass members of struct variables to functions computeGPA(s1.gpa); May pass entire struct variables to functions showData(s5); Can use reference parameter if function needs to modify contents of structure variable

69 Chapter 8 Starting Out with C++: Early Objects 5/e slide 69 © 2006 Pearson Education. All Rights Reserved #include #include // Needed for the pow function using namespace std; struct Circle{ double radius; double diameter; double area; }; void fetchInfo(Circle &round); const double PI = 3.14159; int main(){ Circle c1; fetchInfo(c1); cout<<"The Radius is "<<c1.radius<<"\n The Area is "<<c1.area; return 0; }

70 Chapter 8 Starting Out with C++: Early Objects 5/e slide 70 © 2006 Pearson Education. All Rights Reserved void fetchInfo(Circle &round) { cout << "Enter the diameter of a circle: "; cin >> round.diameter; round.radius = round.diameter / 2; round.area=round.radius*round.radius*PI; }

71 Chapter 8 Starting Out with C++: Early Objects 5/e slide 71 © 2006 Pearson Education. All Rights Reserved 6.13 Using Reference Variables as Parameters Mechanism that allows a function to work with the original argument from the function call, not a copy of the argument Allows the function to modify values stored in the calling environment Provides a way for the function to ‘return’ > 1 value

72 Chapter 8 Starting Out with C++: Early Objects 5/e slide 72 © 2006 Pearson Education. All Rights Reserved Reference Variables A reference variable is an alias for another variable Defined with an ampersand ( & ) void getDimensions(int&, int&); Changes to a reference variable are made to the variable it refers to Use reference variables to implement passing parameters by reference

73 Chapter 8 Starting Out with C++: Early Objects 5/e slide 73 © 2006 Pearson Education. All Rights Reserved Pass by Reference Example void squareIt(int &); //prototype void squareIt(int &num) { num *= num; } int localVar = 5; squareIt(localVar); // localVar’s // value is now 25

74 Chapter 8 Starting Out with C++: Early Objects 5/e slide 74 © 2006 Pearson Education. All Rights Reserved 6.5 Passing Data by Value Pass by value: when argument is passed to a function, a copy of its value is placed in the parameter Function cannot access the original argument Changes to the parameter in the function do not affect the value of the argument back in the calling function

75 Chapter 8 Starting Out with C++: Early Objects 5/e slide 75 © 2006 Pearson Education. All Rights Reserved #include using namespace std; int evenOrOdd(int n){ n=n%2; return n; } int main(){ int n; cin>>n; if (evenOrOdd(n)==1) cout<<“Odd”; else cout << “Even"; return 0; }

76 Chapter 8 Starting Out with C++: Early Objects 5/e slide 76 © 2006 Pearson Education. All Rights Reserved Notes on Passing Structures Using a value parameter for structure can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the structure To save space and time, while protecting structure data that should not be changed, use a const reference parameter void showData(const Student &s) // header

77 Chapter 8 Starting Out with C++: Early Objects 5/e slide 77 © 2006 Pearson Education. All Rights Reserved 7.6 Returning a Structure from a Function Function can return a struct Student getStuData(); // prototype s1 = getStuData(); // call Function must define a local structure −for internal use −to use with return statement

78 Chapter 8 Starting Out with C++: Early Objects 5/e slide 78 © 2006 Pearson Education. All Rights Reserved Returning a Structure Example Student getStuData() { Student s; // local variable cin >> s.studentID; cin.ignore(); getline(cin, s.pData.name); getline(cin, s.pData.address); getline(cin, s.pData.city); cin >> s.year; cin >> s.gpa; return s; }

79 Chapter 8 Starting Out with C++: Early Objects 5/e slide 79 © 2006 Pearson Education. All Rights Reserved #include #include // Needed for the pow function using namespace std; struct Circle{ double radius; double diameter; double area; }; Circle getInfo(); const double PI = 3.14159; int main(){ Circle c1; c1 = getInfo(); cout<<"The Radius is "<<c1.radius<<"\n The Area is "<<c1.area; return 0; }

80 Chapter 8 Starting Out with C++: Early Objects 5/e slide 80 © 2006 Pearson Education. All Rights Reserved Circle getInfo() { Circle round; cout << "Enter the diameter of a circle: "; cin >> round.diameter; round.radius = round.diameter / 2; round.area=round.radius*round.radius*PI; return round; }

81 Chapter 8 Starting Out with C++: Early Objects 5/e slide 81 © 2006 Pearson Education. All Rights Reserved #include using namespace std; const double PI = 3.1; struct Circle{ double radius; double diameter; double area; Circle(double r){ radius=r; diameter=2.0*r; area=r*r*PI; } }; void doubleRadius(Circle &c); int main(){ Circle c1(1.0), c2(2.0); doubleRadius(c1); cout<<"\n c1 Radius is "<<c1.radius<<" c1 diameter is "<<c1.diameter; cout<<"\n c2 Radius is "<<c2.radius<<" c2 diameter is "<<c2.diameter; return 0; }

82 Chapter 8 Starting Out with C++: Early Objects 5/e slide 82 © 2006 Pearson Education. All Rights Reserved void doubleRadius(Circle &round) { round.radius=2.0*round.radius; round.diameter = 2.0*round.radius; round.area=round.radius*round.radius*PI; } Problem: Give the outputs for the program

83 Chapter 8 Starting Out with C++: Early Objects 5/e slide 83 © 2006 Pearson Education. All Rights Reserved 7.4 Nested Structures A structure can have another structure as a member. struct PersonInfo { string name, address, city; }; struct Student { int studentID; PersonInfo pData; short year; double gpa; };

84 Chapter 8 Starting Out with C++: Early Objects 5/e slide 84 © 2006 Pearson Education. All Rights Reserved Members of Nested Structures Use the dot operator multiple times to dereference fields of nested structures Student s5; s5.pData.name = "Joanne"; s5.pData.city = "Tulsa";

85 Starting Out with C++: Early Objects 5/e© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 7 Structured Data and Classes


Download ppt "C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 10: Records ( struct s)"

Similar presentations


Ads by Google