1 / 52

C++ Programming: Program Design Including Data Structures, Second Edition

C++ Programming: Program Design Including Data Structures, Second Edition. Chapter 10: Records (structs). Objectives. In this chapter you will: Learn about records (structs) Examine various operations on a struct Explore ways to manipulate data using a struct

Download Presentation

C++ Programming: Program Design Including Data Structures, Second Edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Programming: Program Design Including Data Structures, Second Edition Chapter 10: Records (structs)

  2. Objectives 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 • Learn how to create an array of struct items • Discover how arrays are used in a struct C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  3. floating address float double long double pointer reference C++ Data Types simple structured integral enum array struct union class char short int long bool C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  4. Records (structs) • Struct: • collection of a fixed number of components, • accessed by name • Components may be of different types • Components of a struct are called the members of the struct • struct is a reserved word C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  5. Records (structs) (continued) • The general syntax of a struct is: struct structName { dataType1 identifier1; dataType2 identifier2; . . . dataTypen identifiern; }; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  6. struct type Declaration SYNTAX struct TypeName // does not allocate memory { MemberList } ; MemberList SYNTAX DataType MemberName ; DataType MemberName ; . . . expanded by J. Goetz, 2004

  7. Accessing struct Members • The syntax for accessing a struct member is: structVariableName.memberName • The dot (.) is an operator, called the member access operator C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  8. 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 ; } ; AnimalType thisAnimal ; // declare variables of AnimalType and AnimalType anotherAnimal ; // allocate memory 8 expanded by J. Goetz, 2004

  9. thisAnimal 5000 .id 2037581 .name “giant panda” .genus “Ailuropoda” .species “melanoluka” .country “China” .age 18 .weight 234.6 .health Good expanded by J. Goetz, 2004

  10. anotherAnimal 6000 .id 5281003 .name “llama” .genus “Lama” .species “peruana” .country “Peru” .age 7 .weight 278.5 .health Excellent Access: thisAnimal.weight anotherAnimal.country expanded by J. Goetz, 2004

  11. Example: //declaration studentType newStudent, student; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  12. More aboutstruct 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. • 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. expanded by J. Goetz, 2004

  13. Assignment • structvariable can be assigned to another struct variable of the same type • The statement: student = newStudent; • copies the contents of newStudent into student C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  14. Comparison (Relational Operators) • Compare struct variables member-wise • To compare the values of student and newStudent: if(student.firstName == newStudent.firstName && student.lastName == newStudent.lastName) . . . C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  15. Input/Output • No aggregate input/output operations on a struct variable • Data in a struct variable must be read/written one member at a time C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  16. Valid operations on a struct member depend only on its type 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++; expanded by J. Goetz, 2004

  17. Aggregatestruct Operations • I/O, arithmetic, and comparisons of entire struct variables are NOT ALLOWED! • operations valid on an entire struct type variable: 1. assignment to another struct variable of same type, 2. pass to a function as argument • by valueor • by reference 3. return as value of a function expanded by J. Goetz, 2004

  18. 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 THE 3 FUNCTIONS USED HERE . . . expanded by J. Goetz, 2004

  19. // ref 2. pass to function by value void WriteOut( /* in */ AnimalType thisAnimal) // Prints out values of all members of thisAnimal, //aggregated I/O is not permited // 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 ) ; } 19 expanded by J. Goetz, 2004

  20. Passing a struct Type by Reference //ref 2. by reference void ChangeAge ( /* inout */ AnimalType& thisAnimal ) // Adds 1 to age // Precondition: thisAnimal.age is assigned // Postcondition: thisAnimal.age == thisAnimal.age@entry + 1 { thisAnimal.age++ ; } expanded by J. Goetz, 2004

  21. // ref3. return as value of a function AnimalType GetAnimalData ( void ) // Obtains all information about an animal from keyboard //aggregated I/O is not permited // Postcondition: // Function value == AnimalType members entered at kbd { AnimalType thisAnimal ; char response ; do { // have user enter all members until they are correct cout << “Enter the animal ID”; cin >> thisAnimal.id; . . . } while (response != ‘Y’ ) ; return thisAnimal ; } 21 expanded by J. Goetz, 2004

  22. Hierarchical Structures • The type of a struct member can be another struct type – structs within a struct • This is called nested or hierarchical structures . • Hierarchical structures are very useful when there is much detailed information in each record. FOR EXAMPLE . . . expanded by J. Goetz, 2004

  23. struct MachineRec • Information about each machine in a shop contains: idNumber description failure rate last service date days down purchase date cost We can reorganize into a hierarchical structure which is easier to manage: • we have two dates – the same logical entities and • a history record (failure rate, date of last service and number of days down) and • the overall record containing dates and cost. expanded by J. Goetz, 2004

  24. struct DateType { int month ; // Assume 1 . . 12 int day ;// Assume 1 . . 31 int year ; // Assume 1900 . . 2050 }; 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 ; 24 expanded by J. Goetz, 2004

  25. struct type variable machine 7000 5719 “DRILLING…” 3 21 1995 8000.0 .02 1 25 1999 4 .month .day .year .month .day .year .failrate .lastServiced .downdays .idNumber .description . history .purchaseDate .cost machine.history.lastServiced.year has value 1999 expanded by J. Goetz, 2004

  26. structs within a structexample p.514 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  27. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  28. Arraysin structs • Two key items are associated with a list: • Values (elements) • Length of the list • Define a struct containing both items p.508: const arraySize = 1000; struct listType { int listElem[arraySize]; // array containing the list int listLength; // length of the list }; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  29. employeeType employees[50]; struct employeeType { string firstName; string lastName; int personID; string deptID; double yearlySalary; double monthlySalary; double yearToDatePaid; double monthlyBonus; }; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  30. Array of Structures const int MAX_SIZE = 500 ; enum HealthType { Poor, Fair, Good, Excellent } ; struct AnimalType// declares struct data type { long id ; string name ; string genus ; string species ; string country ; // 8 struct members int age ; float weight ; HealthType health ; } ; AnimalType bronxZoo [ MAX_SIZE ] ; // declares array 30 expanded by J. Goetz, 2004

  31. AnimalType bronxZoo[MAX_SIZE]; bronxZoo [ 0 ] [ 1 ] . . . . . . [ 498 ] [ 499 ] bronxZoo [ 0 ].id 3456219 bronxZoo [ 0 ].name “camel” bronxZoo [ 0 ].genus “Camelus” bronxZoo [ 0 ].species “dromedarius” bronxZoo [ 0 ].country “India” bronxZoo [ 0 ].age 10 bronxZoo [ 0 ].weight 992.8 bronxZoo [ 0 ].health Fair expanded by J. Goetz, 2004

  32. AnimalType bronxZoo[MAX_SIZE]; .id .name .genus .species .country .age .weight .health bronxZoo [ 0 ] 3456219 “camel” “Camelus”“dromedarius” “India” 10 992.8 Fair bronxZoo [ 1 ] bronxZoo [ 2 ] bronxZoo [ 3 ] . . . . . . bronxZoo[498] bronxZoo[499] expanded by J. Goetz, 2004

  33. Add 1 to the age member of each element of the bronxZoo array for ( j = 0 ; j < MAX_SIZE ; j++ ) bronxZoo[ j ].age = bronxZoo[ j ].age + 1 ; OR, for ( j = 0 ; j < MAX_SIZE ; j++ ) bronxZoo[ j ].age++ ; expanded by J. Goetz, 2004

  34. Find total weight of all elements of the bronxZoo array float total = 0.0 ; for ( j = 0 ; j < MAX_SIZE ; j++ ) total += bronxZoo[ j ].weight ; expanded by J. Goetz, 2004

  35. Example – Problem Statement step I • 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 • Output: At the end of each year, the manager of the company asks for a report C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  36. 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) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  37. Input/Output • Input: • file containing each salesperson’s ID, and • a second file containing the sales data • The sales data is in the following form: salesPersonID month saleAmount . . . • Sales data are not ordered • Output: file containing annual sales report in the above format C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  38. Problem Analysis – Variables step II • Main components for each sales person in the output: • ID • Quarterly sales amount • Total annual sales amount • Because the components are of different types, group them in a struct salesPersonRec • Because the program requires the company’s total sales for each quarter • We need an array of four components to store the Quarterly sales amount: doublesaleByQuarte[4] C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  39. There are six people, so an array of 6 components is used • salesPersonRec salesPersonList [ noOfSalesPersons]; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  40. Problem Analysis – Variables step II ----------- 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 • For calculating the Total we need double totalSaleByQuarter [4]; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  41. Algorithm Design step III • Translates into the following algorithm • Initialize the array salessalesPersonList • Process the sales data by filling out salesPersonList • 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: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  42. 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 • 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 • Open the output file • Output data to two decimal places • Process sales data • Call the function getData 16. Calculate the total saleby 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 • Find and print the quarter producing themaximum sale for the year by calling the function maxSaleByQuarter • Close files C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  43. //Program: Sales data analysis #include <iostream> #include <fstream> #include <iomanip> #include <string> usingnamespace std; constintnoOfSalesPerson = 6; structsalesPersonRec { string ID; //sales person's ID doublesaleByQuarter[4]; double totalSale; }; voidinitialize(ifstream& indata, salesPersonRec list[], intlistSize); voidgetData(ifstream& infile, salesPersonRec list[], intlistSize); voidsaleByQuarter(salesPersonRec list[], intlistSize, double totalByQuarter[]); voidtotalSaleByPerson(salesPersonRec list[], intlistSize); voidprintReport(ofstream& outfile, salesPersonRec list[], intlistSize, double saleByQuarter[]); voidmaxSaleByPerson(ofstream& outData, salesPersonRec list[], intlistSize); voidmaxSaleByQuarter(ofstream& outData, double saleByQuarter[]); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  44. int main() { //Step 1 ifstream infile; //input file stream variable ofstream outfile; //output file stream variable string inputFile; //variable to hold the input file name string outputFile; //variable to hold the output file name double totalSaleByQuarter[4]; //array to hold the sale by quarter salesPersonRec salesPersonList[noOfSalesPerson]; //array to hold the salesperson's data cout << "Enter the salesPerson ID file name: "; //Step 2 cin >> inputFile; //Step 3 cout << endl; infile.open(inputFile.c_str()); //Step 4 if (!infile) //Step 5 { cout << "Cannot open the input file." << endl; return 1; } initialize(infile, salesPersonList, noOfSalesPerson); //Step 6 infile.close(); //reclaim the input file stream variable; Step 7 infile.clear(); //clear the input stream//Step 7 cout << "Enter the sales data file name: "; //Step 8 cin >> inputFile; //Step 9 cout << endl; infile.open(inputFile.c_str()); //Step 10 if (!infile) //Step 11 { cout << "Cannot open the input file." << endl; return 1; } cout << "Enter the output file name: "; //Step 12 cin >> outputFile; //Step 13 cout << endl; outfile.open(outputFile.c_str()); //Step 14 • 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 • 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 • Open the output file C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  45. outfile << fixed << showpoint << setprecision(2); //Step 15 getData(infile, salesPersonList, noOfSalesPerson); //Step 16 saleByQuarter(salesPersonList, noOfSalesPerson, totalSaleByQuarter); //Step 17 totalSaleByPerson(salesPersonList, noOfSalesPerson); //Step 18 printReport(outfile, salesPersonList, noOfSalesPerson, totalSaleByQuarter); //Step 19 maxSaleByPerson(outfile, salesPersonList, noOfSalesPerson); //Step 20 maxSaleByQuarter(outfile, totalSaleByQuarter); //Step 21 infile.close(); //Step 22 outfile.close(); //Step 22 return 0; } voidinitialize(ifstream& indata, salesPersonRec list[], int listSize) { int index; int quarter; for (index = 0; index < listSize; index++) { indata >> list[index].ID; //get salesperson's ID for (quarter = 0; quarter < 4; quarter++) list[index].saleByQuarter[quarter] = 0.0; list[index].totalSale = 0.0; } } • 15. Output data to two decimal places • 16. Process sales data • Call the function getData • 17. Calculate the total saleby quarter by calling the function saleByQuarter • 18. Calculate the total sale by salesman by calling the function totalSaleByPerson • 19. Print the report in the tabular form. Call the function printReport • 20. Find and print the salesperson who produces the maximum sales for the year by calling the function maxSaleByPerson • 21. Find and print the quarter producing themaximum sale for the year by calling the function maxSaleByQuarter • 22. Close files 12345 32214 23422 57373 35864 54654 • Read the salespeople IDs into the array salesPersonList • Initialize the quarterly sales and total sales for each salesperson to 0 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  46. For each entry in the file containing the sales data salesPersonList • 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 voidgetData(ifstream& infile, salesPersonRec list[], int listSize) { int index; int quarter; string sID; int month; double amount; infile >> sID; //get salesperson's ID while (infile) { infile >> month >> amount; //get the sale month and //the sale amount for (index = 0; index < listSize; index++) if (sID == list[index].ID) break; if (1 <= month && month <= 3) quarter = 0; elseif (4 <= month && month <= 6) quarter = 1; elseif (7 <= month && month <= 9) quarter = 2; else quarter = 3; if (index < listSize) list[index].saleByQuarter[quarter] += amount; else cout << "Invalid salesperson's ID." << endl; infile >> sID; }//end while } 12345 1 893 32214 1 343 23422 3 903 57373 2 893 35864 5 329 54654 9 392 12345 2 999 32214 4 892 23422 4 895 23422 2 492 57373 6 892 35864 10 1223 54654 11 3420 12345 12 322 35864 5 892 54654 3 893 12345 8 494 32214 8 9023 23422 6 223 23422 4 783 57373 8 8834 35864 3 2882 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  47. voidsaleByQuarter(salesPersonRec list[], int listSize, double totalByQuarter[]) { int quarter; int index; for (quarter = 0; quarter < 4; quarter++) totalByQuarter[quarter] = 0.0; for (quarter = 0; quarter < 4; quarter++) for (index = 0; index < listSize; index++) totalByQuarter[quarter] += list[index].saleByQuarter[quarter]; } voidtotalSaleByPerson(salesPersonRec list[], int listSize) { int index; int quarter; for (index = 0; index < listSize; index++) for (quarter = 0; quarter < 4; quarter++) list[index].totalSale += list[index].saleByQuarter[quarter]; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  48. voidprintReport(ofstream& outfile, salesPersonRec list[], int listSize, double saleByQuarter[]) { int index; int quarter; outfile << "----------- Annual Sales Report -------------" << endl; outfile << endl; outfile << " ID QT1 QT2 QT3 " << "QT4 Total" << endl; outfile << "________________________________________________" << "_______________" << endl; for (index = 0; index < listSize; index++) { outfile << list[index].ID << " "; for (quarter = 0; quarter < 4; quarter++) outfile << setw(10) << list[index].saleByQuarter[quarter]; outfile << setw(10) << list[index].totalSale << endl; } outfile << "Total "; for (quarter = 0; quarter < 4; quarter++) outfile << setw(10) << saleByQuarter[quarter]; outfile << endl << endl; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  49. voidmaxSaleByPerson(ofstream& outData, salesPersonRec list[], int listSize) { int maxIndex = 0; int index; for (index = 1; index < listSize; index++) if (list[maxIndex].totalSale < list[index].totalSale) maxIndex = index; outData << "Max Sale by SalesPerson: ID = " << list[maxIndex].ID << ", Amount = $" << list[maxIndex].totalSale << endl; } voidmaxSaleByQuarter(ofstream& outData, double saleByQuarter[]) { int quarter; int maxIndex = 0; for (quarter = 0; quarter < 4; quarter++) if (saleByQuarter[maxIndex] < saleByQuarter[quarter]) maxIndex = quarter; outData << "Max Sale by Quarter: Quarter = " << maxIndex + 1 << ", Amount = $" << saleByQuarter[maxIndex] << endl; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  50. Summary • 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 (fields) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

More Related