CHAPTER 12 RECORDS (Structs) - PowerPoint PPT Presentation

1 / 66
About This Presentation
Title:

CHAPTER 12 RECORDS (Structs)

Description:

CHAPTER 12 RECORDS (Structs) In this chapter, you will: Learn about records (structs) Examine various operations on a struct Explore ways to manipulate data using a ... – PowerPoint PPT presentation

Number of Views:103
Avg rating:3.0/5.0
Slides: 67
Provided by: abc7266
Category:

less

Transcript and Presenter's Notes

Title: CHAPTER 12 RECORDS (Structs)


1
CHAPTER 12RECORDS (Structs)
2
  • 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

3
  • Records (Struct)
  • struct A collection of fixed number of
    components in which components are accessed by
    name is called a struct. The components may be of
    different types.
  • The components of a struct are called the members
    of the struct.
  • The general form (syntax) of a struct in C is
  • struct typeName
  • dataType1 identifier1
  • dataType2 identifier2
  • .
  • .
  • .
  • dataTypen identifiern

4
  • In C, struct is a reserved word.
  • A semicolon at the end of a struct definition is
    a part of the syntax.

5
  • struct employeeType
  • string firstName
  • string lastName
  • string address1
  • string address2
  • double salary
  • string deptID
  • struct is a definition not a declaration. No
    memory is allocated.
  • Memory is allocated when we declare variables.

6
  • struct studentType
  • string firstName
  • string lastName
  • char courseGrade
  • int testScore
  • int programmingScore
  • double GPA
  • //variable declaration
  • studentType newStudent
  • studentType student

7
(No Transcript)
8
  • Accessing struct Members
  • The syntax for accessing a struct member is
  • structVariableName.MemberName
  • In C, the . (dot) is an operator, called the
    member access operator.

9
  • newstudent.gpa 0.0
  • newStudent.firstName "John"
  • newStudent.lastName "Brown"

10
  • The statement
  • cingtgtnewstudent.firstName
  • reads the next string from the standard input
    device and stores it in newstudent.firstName.
  • The statement
  • cingtgtnewstudent.testScoregtgtnewstudent.programmingS
    core
  • reads two integer values from the keyboard and
    stores them in newStudent.testScore and
    newStudent.programmingScore, respectively.
  • score newStudent.testScore
  • newStudent.programmingScore

11
  • if(score gt 90)
  • newStudent.courseGrade 'A'
  • else if(score gt 80)
  • newStudent.courseGrade 'B'
  • else if(score gt 70)
  • newStudent.courseGrade 'C'
  • else if(score gt 60)
  • newStudent.courseGrade 'D'
  • else
  • newStudent.courseGrade 'F'

12
  • Assignment
  • We can assign the value of one struct variable to
    another struct variable of the same type using an
    assignment statement.

13
  • student newstudent

14
  • student newstudent
  • This statement 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.programmingS
    core
  • student.GPA newStudent.GPA

15
  • Comparison
  • struct variables must be compared member-wise.
  • To compare the values of student and newStudent,
    you must compare them member-wise, as follows
  • if(student.firstName newStudent.firstName
  • student.lastName newStudent.lastName)
  • .
  • .
  • .

16
  • Input/Output
  • There are no aggregate input/output operations on
    struct.
  • Data in a struct variable must be read one member
    at a time.
  • Contents of a struct must be written one member
    at a time.
  • The statement
  • coutltltnewStudent.firstNameltlt" "
  • ltltnewStudent.lastNameltlt" "
  • ltltnewStudent.courseGradeltlt" "
  • ltltnewStudent.testScoreltlt" "
  • ltltnewStudent.programmingScoreltlt" "
  • ltltnewStudent.GPAltltendl
  • outputs the content of the struct variable
    newstudent.

17
  • struct Variables and Functions
  • A struct variable can be passed as a parameter
    either by value or by reference.
  • A function can return a value of the type struct.

18
  • void readIn(studentType student)
  • int score
  • cingtgtstudent.firstNamegtgtstudent.lastName
  • cingtgtstudent.testScoregtgtstudent.programmingScor
    e
  • cingtgtstudent.GPA
  • score newStudent.testScore
    newStudent.programmingScore
  • if(score gt 90)
  • student.courseGrade 'A'
  • else if(score gt 80)
  • student.courseGrade 'B'
  • else if(score gt 70)
  • student.courseGrade 'C'
  • else if(score gt 60)
  • student.courseGrade 'D'
  • else

19
  • The statement
  • readIn(newStudent)
  • calls the function readIn.
  • The function readIn stores the appropriate
    information in the variable newStudent.

20
  • void printStudent(studentType student)
  • coutltltstudent.firstNameltlt" "
  • ltltstudent.lastNameltlt" "
  • ltltstudent.courseGradeltlt" "
  • ltltstudent.testScoreltlt" "
  • ltltstudent.programmingScoreltlt" "
  • ltltstudent.GPAltltendl

21
(No Transcript)
22
  • Arrays in Structs
  • The two things that are associated with a list
    are the values (that is, elements) and the length
    of the list.
  • In the searching and sorting functions that we
    discussed, we needed to pass these two things
    separately to the function.
  • The values and the length are both related to a
    list we can define a struct containing both the
    items.
  • We need to pass only one parameter not two.

23
  • const arraySize 1000
  • struct listType
  • int elementsarraySize //array containing
    the list
  • int listLength //length of the list

24
  • int seqSearch(const listType list, int
    searchItem)
  • int loc
  • bool found false
  • for(loc 0 loc lt list.listLength loc)
  • if(list.elementsloc searchItem)
  • found true
  • break
  • if(found)
  • return loc
  • else
  • return 1

25
  • Structs in Arrays
  • Suppose there are 50 full time employees in a
    company.
  • Print their monthly pay check and also keep track
    of how much money has been paid year to date.
  • Define an employees record.
  • struct employeeType
  • string firstName
  • string lastName
  • int personID
  • string deptID
  • double yearlySalary
  • double monthlySalary
  • double yearToDatePaid
  • double monthlyBonus

26
  • employeeType employees50

27
  • The following C code loads the data into the
    employees array.
  • We assume that initially yearToDatePaid is 0 and
    that the monthly bonus is determined each month
    based on performance.
  • ifstream infile //input stream variable assume
  • //that employee.dat file has been opened
  • for(counter 0 counter lt 50 counter)
  • infilegtgtemployeescounter.firstName
  • gtgtemployeescounter.lastName
  • gtgtemployeescounter.SSN
  • gtgtemployeescounter.deptID
  • gtgtemployeescounter.yearlySalary
  • employeescounter.monthlySalary
  • employeescounter.yearlySalary/1
    2
  • employeescounter.yearToDatePaid 0.0
  • employeescounter.monthlyBonus 0.0

28
  • double payCheck //variable to calculate the
    paycheck
  • for(counter 0 counter lt 50 counter)
  • coutltltemployeescounter.firstNameltlt" "
  • ltltemployeescounter.lastNameltlt" "
  • payCheck employeescounter.monthlySalary
  • employeescounter.monthlyBonus
  • employeescounter.yearToDatePaid
  • employeescounter.yearToDatePaid
  • payCheck
  • coutltltsetprecision(2)ltltpayCheckltltendl

29
  • Structs within a struct
  • Let us consider the following record of an
    employee
  • struct employeeType
  • string firstname
  • string middlename
  • string lastname
  • string emplID
  • string address1
  • string address2
  • string city
  • string state
  • string zip
  • string hiremonth
  • string hireday
  • string hireyear

30
  • string quitmonth
  • string quitday
  • string quityear
  • string phone
  • string cellphone
  • string fax
  • string pager
  • string email
  • string deptID
  • double salary

31
  • struct nameType
  • string firstname
  • string middlename
  • string lastname
  • struct addressType
  • string address1
  • string address2
  • string city
  • string state
  • string zip

32
  • struct dateType
  • string month
  • string day
  • string year
  • struct contactType
  • string phone
  • string cellphone
  • string fax
  • string pager
  • string email

33
  • struct employeeType
  • nameType name
  • string emplID
  • addressType address
  • dateType hiredate
  • dateType quitdate
  • contactType contact
  • string deptID
  • double salary
  • // variable declaration
  • employeeType newEmployee
  • employeeType employees100

34
  • newEmployee.salary 45678.00
  • newEmployee.name.first "Mary"
  • newEmployee.name.middle "Beth"
  • newEmployee.name.last "Simmons"
  • cingtgtnewEmployee.name.first
  • newEmployee.salary newEmployee.salary 1.05
  • for(j 0 j lt 100 j)
  • cingtgtemployeesj.name.first
  • gtgtemployeesj.name.middle
  • gtgtemployeesj.name.last

35
  • PROGRAMMING EXAMPLE SALES DATA ANALYSIS
  • A company has six salespeople. Every month they
    go on road trips to sell the companys product.
    At the end of each month, the total sales for
    each salesperson, together with that
    salespersons ID and the month, is recorded in a
    file. At the end of each year, the manager of the
    company wants to see the report in the following
    tabular format

36
  • ----------- 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).

37
  • The salespeoples IDs are stored in one file
    sales data are stored in another file. The sales
    data is in the following form
  • salesPersonID month saleAmount
  • .
  • .
  • .
  • The sales data is in no particular order it is
    not ordered by ID.
  • Input One file containing each salespersons ID,
    and a second file containing the sales data.
  • Output A file containing annual sales report in
    the above format.

38
  • Problem Analysis and Algorithm Design
  • struct salesPersonRec
  • string ID //salespersons ID
  • double saleByQuarter4 //array to store the
    total
  • //sales for each quarter
  • double totalSale //salespersons yearly
  • //sales amount
  • salesPersonRec salesPersonListnoOfSalesPersons
  • double totalSaleByQuarter4

39
(No Transcript)
40
  • Read the salespeoples IDs into the array
    salesPersonList and initialize the quarterly
    sales and total sales for each salesperson to 0.

41
  • For each entry in the file containing the sales
    data,
  • 1. Read the salespersons ID, month, and sale
    amount for the month.
  • 2. Search the array salesPersonList to locate the
    component corresponding to this salesperson.
  • 3. Determine the quarter corresponding to the
    month.
  • 4. Update the sales for the quarter by adding the
    sale amount for the month.
  • Once the sales data file is processed
  • a. Calculate the total sale by salesman.
  • b. Calculate the total sale by quarter.
  • c. Print the report.

42
  • The above discussion translates into the
    following algorithm.
  • 1. Initialize the array sales.
  • 2. Process the sales data.
  • 3. Calculate the total sale by salesman.
  • 4. Calculate the total sale by quarter.
  • 5. Print the report.
  • 6. Calculate and print the maximum sale by
    salesman.
  • 7. Calculate and print the maximum sale by
    quarter.

43
  • Function initialize
  • void initialize(ifstream indata,
  • salesPersonRec list, int listSize)
  • int count
  • quarterType quarter
  • for(count 0 count lt listSize count)
  • indatagtgtlistcount.ID //get salespersons ID
  • for(quarter QT1 quarter lt QT4
  • quarter static_castltquarterTypegt(quart
    er 1))
  • listcount.saleByQuarterquarter 0.0
  • listcount.totalSale 0.0

44
  • Function getData
  • 1. Read the salespersons ID, month, and sales
    amount for the month.
  • 2. Search the array salesPersonList to locate the
    component corresponding to the salesperson.
    (Because the salespeoples IDs are not sorted, we
    will use a sequential search to search the
    array.)
  • 3. Determine the quarter corresponding to the
    month.
  • 4. Update the sales for the quarter by adding the
    sales amount for the month.
  • Suppose that the entry read is
  • 57373 2 350
  • Here the salespersons ID is 57373, the month is
    2, and sale amount is 350.

45
(No Transcript)
46
  • After processing this entry the array
    salesPersonList is

47
  • void getData(ifstream infile,
  • salesPersonRec list, int listSize)
  • int count
  • quarterType quarter
  • string sID
  • int month
  • double amount
  • infilegtgtsID //Step 1
  • while(infile)
  • infilegtgtmonthgtgtamount //Step 1
  • for(count 0 count lt listSize count)
    //Step 2

48
  • if(sID listcount.ID)
  • if(1 lt month month lt 3) //Step 3
  • quarter QT1
  • else if(4 lt month month lt 6)
  • quarter QT2
  • else if(7 lt month month lt 9)
  • quarter QT3
  • else
  • quarter QT4
  • listcount.saleByQuarterquarter
    amount
  • //Step 4
  • break //exit for loop
  • //end if
  • //end for
  • infilegtgtsID //Step 1

49
  • Function saleByQuarter
  • void saleByQuarter(salesPersonRec list, int
    listSize,
  • double totalByQuarter)
  • quarterType quarter
  • int count
  • for(quarter QT1 quarter lt QT4
  • quarter static_castltquarterTypegt(quarter
    1))
  • totalByQuarterquarter 0.0
  • for(quarter QT1 quarter lt QT4
  • quarter static_castltquarterTypegt(quarter
    1))
  • for(count 0 count lt listSize count)
  • totalByQuarterquarter
    listcount.saleByQuarterquarter

50
  • Function totalSaleByPerson This function finds
    the yearly sale amount of each salesman sale.
  • void totalSaleByPerson(salesPersonRec list,
  • int listSize)
  • int count
  • quarterType quarter
  • for(count 0 count lt listSize count)
  • //for each salesperson
  • for(quarter QT1 quarter lt QT4 //for each
    quarter
  • quarter static_castltquarterTypegt(quarter
    1))
  • listcount.totalSale
  • listcount.saleByQuarterquarte
    r

51
  • Function printReport
  • 1. Print the heading, that is, the first three
    lines of output.
  • 2. Print the data for each salesperson.
  • 3. Print the last line of the table.

52
  • void printReport(ofstream outfile,
    salesPersonRec list,
  • int listSize, double saleByQuarter)
  • int count
  • quarterType quarter
  • //Step a
  • outfileltlt"----------- Annual Sales Report
    -------------"
  • ltltendl
  • outfileltltendl
  • outfileltlt" ID QT1 QT2 QT3
    "
  • ltlt"QT4 Total"ltltendl
  • outfileltlt"_____________________________________
    ___________"
  • ltlt"_______________"ltltendl
  • for(count 0 count lt listSize
    count) //Step b
  • outfileltltlistcount.IDltlt" "
  • for(quarter QT1 quarter lt QT4

53
  • outfileltlt"Total " //Step c
  • for(quarter QT1 quarter lt QT4
  • quarter static_castltquarterTypegt(qua
    rter 1))
  • outfileltltsetw(10)ltltsaleByQuarterquarter
  • outfileltltendlltltendlltltendl

54
  • Function maxSaleByPerson
  • void maxSaleByPerson(ofstream outData,
  • salesPersonRec list, int
    listSize)
  • int maxIndex 0
  • int count
  • for(count 1 count lt listSize count)
  • if(listmaxIndex.totalSale lt listcount.totalSa
    le)
  • maxIndex count
  • outDataltlt"Max Sale by SalesPerson ID "
  • ltltlistmaxIndex.ID
  • ltlt", Amount "
  • ltltlistmaxIndex.totalSaleltltendl

55
  • Function maxSaleByQuarter
  • void maxSaleByQuarter(ofstream outData,
  • double saleByQuarter)
  • quarterType quarter
  • quarterType maxIndex QT1
  • for(quarter QT1 quarter lt QT4
  • quarter static_castltquarterTypegt(quarte
    r1))
  • if(saleByQuartermaxIndex lt
    saleByQuarterquarter)
  • maxIndex quarter
  • outDataltlt"Max Sale by Quarter Quarter "
  • ltltgstatic_castltintgt(maxIndex) 1
  • ltlt", Amount "ltltsaleByQuartermaxIndexltlten
    dl

56
  • Main Algorithm
  • 1. Declare the variables.
  • 2. Prompt the user to enter the name of the file
    containing the salespersons ID data.
  • 3. Read the name of the input file.
  • 4. Open the input file.
  • 5. If the input file does not exist, exit the
    program.
  • 6. Initialize the array salesPersonList. Call the
    function initialize.
  • 7. Close the input file containing the
    salespersons ID data.
  • 8. Prompt the use to enter the name of the file
    containing sales data.
  • 9. Read the name of the input file.
  • 10. Open the input file.
  • 11. If input file does not exist, exit the
    program.
  • 12. Prompt the user to enter the name of output
    file.
  • 13. Read the name of the output file.

57
  • 14. Open the output file.
  • 15. To output floating-point numbers in a fixed
    decimal format with the decimal point and
    trailing zero, set the manipulators fixed and
    showpoint. Also, to output floating-point numbers
    to two decimal places, set the precision to two
    decimal places.
  • 16. Process sales data. Call the function
    getData.
  • 17. Calculate the total sale by quarter. Call the
    function saleByQuarter.
  • 18. Calculate the total sale by salesman. Call
    the function totalSaleByPerson.
  • 19. Print the report in the tabular form. Call
    function the printReport.
  • 20. Find and print the salesperson who produces
    the maximum sales for the year. Call the function
    maxSaleByPerson.
  • 21. Find and print the quarter producing the
    maximum sale for the year. Call the function
    maxSaleByQuarter.
  • 22. Close files.

58
  • //Program Sales data analysis
  • include ltiostreamgt
  • include ltfstreamgt
  • include ltiomanipgt
  • include ltstringgt
  • using namespace std
  • const int noOfSalesPerson 6
  • enum quarterTypeQT1,QT2,QT3,QT4
  • struct salesPersonRec
  • string ID //salespersons ID
  • double saleByQuarter4
  • double totalSale

59
  • void totalSaleByPerson(salesPersonRec list,
  • int listSize)
  • void maxSaleByPerson(ofstream outData,
  • salesPersonRec list, int
    listSize)
  • void maxSaleByQuarter(ofstream outData,
  • double saleByQuarter)
  • void printReport(ofstream outfile,
  • salesPersonRec list, int listSize,
  • double saleByQuarter)
  • int main()
  • //Step 1
  • ifstream infile //input file stream
    variable
  • ofstream outfile //output file stream
    variable
  • char inputfile25 //variable to hold the
    input file name
  • char outputfile25 //variable to hold the
    output file name
  • double totalSaleByQuarter4 //array to hold
    the
  • //sales by quarter

60
  • coutltlt"Enter SalesPerson ID file name "
    //Step 2
  • cingtgtinputfile //Step 3
  • coutltltendl
  • infile.open(inputfile) //Step 4
  • if(!infile) //Step 5
  • coutltlt"Cannot open input file."ltltendl
  • return 1
  • initialize(infile, salesPersonList,
    noOfSalesPerson)
  • //Step 6
  • infile.close() //Step 7
  • coutltlt"Enter sales data file name "
    //Step 8
  • cingtgtinputfile //Step 9

61
  • if(!infile) //Step 11
  • coutltlt"Cannot open input file."ltltendl
  • return 1
  • coutltlt"Enter output file name " //Step
    12
  • cingtgtoutputfile //Step 13
  • coutltltendl
  • outfile.open(outputfile) //Step 14
  • outfileltltfixedltltshowpointltltsetprecision(2)
    //Step 15
  • getData(infile, salesPersonList,
    noOfSalesPerson)
  • //Step 16
  • saleByQuarter(salesPersonList,
    noOfSalesPerson,
  • totalSaleByQuarter) //Step 17

62
  • maxSaleByPerson(outfile, salesPersonList,
  • noOfSalesPerson) //Step 20
  • maxSaleByQuarter(outfile, totalSaleByQuarter)

  • //Step 21
  • infile.close() //Step 22
  • outfile.close() //Step 22
  • return 0

63
  • //Place the definitions of the other functions
  • //here

64
  • Sample Run
  • Input File Salespeoples IDs
  • 12345
  • 32214
  • 23422
  • 57373
  • 35864
  • 54654

65
  • Input File Salespeoples Data
  • 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

66
  • Output File
  • ----------- 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 SalesMan ID 57373, Amount
    10619.00
  • Max Sale by Quarter Quarter 3, Amount
    18743.00
Write a Comment
User Comments (0)
About PowerShow.com