C++ Programming: Program Design Including Data Structures ...

C++ Programming: Program Design Including Data Structures ...

C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 11: 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 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, Fifth Edition 2 Records (structs) struct: collection of a fixed number of components (members), accessed by name Members may be of different types

Syntax: C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 Records (structs) (cont'd.) A struct is a definition, not a declaration C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4

Records (structs) (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 Accessing struct Members The syntax for accessing a struct member is: The dot (.) is an operator, called the member access operator

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 6 Accessing struct Members (cont'd.) To initialize the members of newStudent: newStudent.GPA = 0.0; newStudent.firstName = "John"; newStudent.lastName = "Brown"; C++ Programming: From Problem Analysis to Program Design, Fifth Edition

7 Accessing struct Members (cont'd.) More examples: cin >> newStudent.firstName; cin >> newStudent.testScore >> newStudent.programmingScore; score = (newStudent.testScore + newStudent.programmingScore) / 2; C++ Programming: From Problem Analysis to Program Design, Fifth Edition

8 Accessing struct Members (cont'd.) if (score >= 90) newStudent.courseGrade else if (score >= 80) newStudent.courseGrade else if (score >= 70) newStudent.courseGrade else if (score >= 60) newStudent.courseGrade else

newStudent.courseGrade = 'A'; = 'B'; = 'C'; = 'D'; = 'F'; C++ Programming: From Problem Analysis to Program Design, Fifth Edition 9 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 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 10

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;

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 11 Comparison (Relational Operators) Compare struct variables memberwise No aggregate relational operations allowed To compare the values of student and newStudent: C++ Programming: From Problem Analysis to Program Design, Fifth Edition

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

13 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, Fifth Edition 14 Arrays versus structs

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 15 Arrays in structs Two key items are associated with a list: Values (elements) Length of the list Define a struct containing both items: C++ Programming: From Problem Analysis to Program Design, Fifth Edition

16 Arrays in structs (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 17 Arrays in structs (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition

18 structs in Arrays C++ Programming: From Problem Analysis to Program Design, Fifth Edition 19 structs in Arrays (contd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 20

structs in Arrays (contd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 21 structs within a struct versus C++ Programming: From Problem Analysis to Program Design, Fifth Edition

22 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, salespersons 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, Fifth Edition

23 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) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 24 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 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 25 Programming Example: Input/Output Input: file containing each salespersons 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, Fifth Edition 26 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 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 27 Programming Example: Problem Analysis (cont'd.) C++ Programming: From Problem Analysis to Program Design, Fifth Edition

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

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

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

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

32 Programming Example: Main Algorithm Declare the variables Prompt user to enter name of file containing the salespersons 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, Fifth Edition

33 Programming Example: Main Algorithm (cont'd.) Close input file containing salespersons 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, Fifth Edition 34 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 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 35 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 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 36 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 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 37 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 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 38

Recently Viewed Presentations

  • Chemical Pathology Revision Lecture Dr Shivam Patel Shivam.Patel@doctors.org.uk

    Chemical Pathology Revision Lecture Dr Shivam Patel [email protected]

    Vaptans = ADH antagonists. Useful in resistant SIADH. Cost! Very rarely… Hypertonic saline. Euvolaemic are all endocrine. Hypothyroid, cortisol deficiency. Urine sodium always high because SIADH is high
  • Performing Operations on Polynomials - Virginia Department of ...

    Performing Operations on Polynomials - Virginia Department of ...

    The first standard highlighted is SOL A.2. For this standard students need additional practice performing operations on polynomials including: a) applying the laws of exponents to perform operations on expressions, b) dividing polynomials, and c) factoring completely first- and second-degree...
  • Btec First Diploma in Sport

    Btec First Diploma in Sport

    P5 - interpret their test results and personal level of fitness. M2 - explain their test results and personal level of fitness, identifying strengths and areas for improvement. D1 - evaluate their test results and personal level of fitness, considering...
  • Apresentação do PowerPoint

    Apresentação do PowerPoint

    Aspectos comerciais Parte 2/3 Apoio Realização Oportunidades Presença da MPE na Internet/Web pode: reduzir custos atendimento a cliente, estoque, staff, ... simplificar infra-estrutura expandir rede de parceiros aumentar mercados/vendas exportação Estudo "Termômetro Empresarial" (Arthur Andersen,15a.
  • LIN 1180  Semantics Lecture 8 Albert Gatt Part

    LIN 1180 Semantics Lecture 8 Albert Gatt Part

    if Y is a hyponym of X then Y contains the meaning of X (plus something extra) e.g. MAN includes all the features of HUMAN, plus the specification of ADULT and MALE. Transitivity: if X IS-A Y and Y IS-A...
  • Shooting Stars Notes on poem and critical essay

    Shooting Stars Notes on poem and critical essay

    Shooting Stars Notes on poem and critical essay advice Purpose of the Critical Essay Features of a Critical Essay Assessment of a Critical Essay UNDERSTANDING ANALYSIS EVALUATION EXPRESSION 2003, Q14 Choose a poem in which the poet has created a...
  • Legislation

    Legislation

    The Salamanca Statement 1994. representatives of 92 governments and 25 international organisations formed the World Conference on Special Needs Education, held in Salamanca, Spain. They agreed a dynamic new Statement on the education of all disabled children, which called for...
  • Acid-base titration properties

    Acid-base titration properties

    Gran plot uses data from before the end point to find the end point. Consider the titration of a weak acid: HA ↔ H+ + A- 11-6 Finding the end point with indicators Indicator itself is an acid or base...