Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10: Records (structs)

Similar presentations


Presentation on theme: "Chapter 10: Records (structs)"— Presentation transcript:

1 Chapter 10: Records (structs)
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 10: Records (structs)

2 Objectives In this chapter you will: Learn about records (structs)
In this chapter you will: Learn about records (structs) 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 C++ Programming: From Problem Analysis to Program Design, Second Edition

3 C++ Data Types simple structured address integral enum floating
simple structured integral enum floating float double long double array struct union class char short int long bool address pointer reference C++ Programming: From Problem Analysis to Program Design, Second Edition

4 C++ Data Types There are simple data types that hold only one value
There are simple data types that hold only one value There are structured data types that hold multiple values The array was the first example of a structured data type that can hold multiple values The structure is the second example C++ Programming: From Problem Analysis to Program Design, Second Edition

5 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

6 C++ Structured Type often we have related information of various types that we’d like to store together for convenient access under the same identifier, for example . . .

7 thisAnimal 5000 .id 2037581 .name “giant panda” .genus “Ailuropoda”
5000 .id .name “giant panda” .genus “Ailuropoda” .species “melanoluka” .country “China” .age .weight .health Good

8 anotherAnimal 6000 .id 5281003 .name “llama” .genus “Lama”
6000 .id .name “llama” .genus “Lama” .species “peruana” .country “Peru” .age .weight .health “Excellent”

9 struct AnimalType struct AnimalType // declares a struct data type
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 ; string health ; } ; // NOTE THE SEMICOLON AnimalType thisAnimal ; // declare variables of AnimalType AnimalType anotherAnimal ; 9

10 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.

11 More about struct type declarations
More about struct type declarations If the struct type declaration precedes all functions it will be visible throughout the rest of the file. If it is placed within a function, only that function can use it. It is common to place struct type declarations with TypeNames in a (.h) header file and #include that file (more on this later). It is possible for members of different struct types to have the same identifiers. Also a non-struct variable may have the same identifier as a structure member.

12 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

13 Valid operations on a struct member depend only on its type
thisAnimal.age = 18; thisAnimal.id = ; cin >> thisAnimal.weight; getline ( cin, thisAnimal.species ); thisAnimal.name = “giant panda”; thisAnimal.genus[ 0 ] = toupper (thisAnimal.genus[ 0 ] ) ; thisAnimal.age++;

14 Aggregate Operation is an operation on a data structure as a whole, as opposed to an operation on an individual component of the data structure

15 Aggregate struct Operations
I/O, arithmetic, and comparisons of entire struct variables are NOT ALLOWED! Operations valid on an entire struct type variable: assignment to another struct variable of same type, pass to a function as argument (by value or by reference), return as value of a function

16 Examples of aggregate struct operations
Examples of aggregate struct operations anotherAnimal = thisAnimal ; // assignment WriteOut(thisAnimal); // value parameter ChangeWeightAndAge(thisAnimal); // reference parameter thisAnimal = GetAnimalData( ); // return value of function NOW WE’LL WRITE FUNCTIONS USED HERE . . .

17 void WriteOut( /* in */ AnimalType thisAnimal)
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 ; cout << “General health : “ ; WriteWord ( thisAnimal.health ) ; } 17

18 Passing a struct Type by Reference
void ChangeAge ( /* inout */ AnimalType& thisAnimal ) // Adds 1 to age // Precondition: thisAnimal.age is assigned // Postcondition: thisAnimal.age == + 1 { thisAnimal.age++ ; }

19 AnimalType GetAnimalData ( void )
AnimalType GetAnimalData ( void ) // Obtains all information about an animal from keyboard // Postcondition: // Function value == AnimalType members entered at kbd { AnimalType thisAnimal ; char response ; do { // have user enter all members until they are correct . } while (response != ‘Y’ ) ; return thisAnimal ; } 19

20 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 . . .

21 struct MachineRec Information about each machine in a shop contains:
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).

22 struct StatisticsType { float failRate ;
struct DateType { int month ; // Assume int day ; // Assume int year ; // Assume }; 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 type DateType purchaseDate ; float cost ; MachineRec machine ; 22

23 struct type variable machine
7000 5719 “DRILLING…” .month .day .year .failrate .lastServiced .downdays .month .day .year .idNumber .description . history purchaseDate cost machine.history.lastServiced.year has value 1999

24 Another Struct Example
An example of a studentData struct: struct studentData { string firstName; string lastName; char courseGrade; float testScore; float programmingScore; float GPA; }; // NOTE THE SEMICOLON C++ Programming: From Problem Analysis to Program Design, Second Edition

25 Declaring a struct After you have defined a struct, you can declare variables in your program to be a that struct: studentData student; studentData newStudent; C++ Programming: From Problem Analysis to Program Design, Second Edition

26

27 Assignment You can copy one structure to another if they are the same type of student = newStudent; You can copy individual members: newStudent.lastName = student.lastName Or into a variable of the correct type: thisStudentName = student.lastName; C++ Programming: From Problem Analysis to Program Design, Second Edition

28 Comparison (Relational Operators)
Compare struct variables member-wise (NOT THE WHOLE STRUCTURE) To compare the values of student and newStudent: if(student.firstName == newStudent.firstName && student.lastName == newStudent.lastName) . C++ Programming: From Problem Analysis to Program Design, Second Edition

29 Input/Output No aggregate input/output operations on a struct variable
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 C++ Programming: From Problem Analysis to Program Design, Second Edition

30 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 C++ Programming: From Problem Analysis to Program Design, Second Edition

31

32 Arrays in structs Two key items are associated with a list:
Two key items are associated with a list: Values (elements) Length of the list Define a struct containing both items: const arraySize = 1000; struct listType { int listElem[arraySize]; //array containing the list int listLength; //length of the list }; C++ Programming: From Problem Analysis to Program Design, Second Edition

33

34

35 Programming Example A company has six salespeople
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 C++ Programming: From Problem Analysis to Program Design, Second Edition

36 Output Format Annual Sales Report ID QT QT QT QT4 Total _______________________________________________________________ Total Max Sale by SalesPerson: ID = 57373, Amount = $ Max Sale by Quarter: Quarter = 3, Amount = $ 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) C++ Programming: From Problem Analysis to Program Design, Second Edition

37 Programming Example 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 C++ Programming: From Problem Analysis to Program Design, Second Edition

38 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 C++ Programming: From Problem Analysis to Program Design, Second Edition

39 Problem Analysis Main components for each sales person:
Main components for each sales person: ID Quarterly sales amount Total annual sales amount Because the components are of different types, group them in a struct C++ Programming: From Problem Analysis to Program Design, Second Edition

40 Program Analysis (continued)
There are six people, so an array of 6 components is used Because the program requires the company’s total sales for each quarter We need an array of four components to store the data C++ Programming: From Problem Analysis to Program Design, Second Edition

41

42 Program Analysis (continued)
Read the salespeople IDs into the array salesPersonList Initialize the quarterly sales and total sales for each salesperson to 0 C++ Programming: From Problem Analysis to Program Design, Second Edition

43 Program Analysis (continued)
For each entry in the file containing 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 C++ Programming: From Problem Analysis to Program Design, Second Edition

44 Program Analysis (continued)
Once the sales data file is processed Calculate the total sale by salesman Calculate the total sale by quarter Print the report C++ Programming: From Problem Analysis to Program Design, Second Edition

45 Algorithm Design Translates into the following algorithm
Translates into the following algorithm Initialize the array sales Process the sales data Calculate the total sale by salesman Calculate the total sale by quarter Print the report Calculate and print maximum sale by salesman Calculate and print maximum sale by quarter C++ Programming: From Problem Analysis to Program Design, Second Edition

46 Main Algorithm Declare the variables
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 C++ Programming: From Problem Analysis to Program Design, Second Edition

47 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 C++ Programming: From Problem Analysis to Program Design, Second Edition

48 Main Algorithm (continued)
Open the output file Output data to two decimal places Process sales data Call the function getData C++ Programming: From Problem Analysis to Program Design, Second Edition

49 Main Algorithm (continued)
Calculate the total sale by quarter by calling the function saleByQuarter Calculate the total sale by salesman by calling the function totalSaleByPerson 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 the function maxSaleByPerson C++ Programming: From Problem Analysis to Program Design, Second Edition

50 Main Algorithm (continued)
Find and print the quarter producing the maximum sale for the year by calling the function maxSaleByQuarter Close files C++ Programming: From Problem Analysis to Program Design, Second Edition

51 Organization of Large Programs
Large programs are composed of multiple source files. Each source file is compiled by dev-C++ then linked into an executable program So that struct definitions can be used in all the source files, they are put in header (include files) The header file is then included in the source file C++ Programming: From Problem Analysis to Program Design, Second Edition

52 Include Files The #include statement inserts the named file in this source code file It is typically used for definitions needed by the source file Structures are the first example of the need for you to use your own include file Using include files means that you only define the structure once no matter how many files it is used in C++ Programming: From Problem Analysis to Program Design, Second Edition

53 Include File Example // Functions for the sales by quarter program
// Functions for the sales by quarter program #include <iostream> // system runtime files #include <fstream> #include <iomanip> #include <string> using namespace std; #include "salesPerson.h" // sales person header file C++ Programming: From Problem Analysis to Program Design, Second Edition

54 System Includes vs. User Includes
Note how system files are included: #include <iostream> // using angle brackets Note how your header files are included: using namespace std; #include "salesPerson.h" Put inside double quotes after the using statement C++ Programming: From Problem Analysis to Program Design, Second Edition

55 Summary Struct: collection of a fixed number of components
Struct: collection of a fixed number of components Components can be of different types struct is a reserved word No memory is allocated for a struct; memory is allocated for struct variables when declared Components of a struct are called members C++ Programming: From Problem Analysis to Program Design, Second Edition

56 Summary struct components are accessed by name
struct components are accessed by name Dot (.) operator is called the member access operator Members of a struct are accessed using the dot (.) operator The only built-in operations on a struct are the assignment and member access C++ Programming: From Problem Analysis to Program Design, Second Edition

57 Summary Neither arithmetic nor relational operations are allowed on the entire structure structures can be passed by value or reference A function can return a structure A structure can be a member of another structure C++ Programming: From Problem Analysis to Program Design, Second Edition


Download ppt "Chapter 10: Records (structs)"

Similar presentations


Ads by Google