1 CS102 Introduction to Computer Programming Chapter 11 Structured Data.

Slides:



Advertisements
Similar presentations
Starting Out with C++, 3 rd Edition 1 Chapter 11 – Structured Data Abstract data types (ADTs) are data types created by the programmer. ADTs have their.
Advertisements

Starting Out with C++: Early Objects 5th Edition
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
Chapter 11 – Structured Data
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 10 Structured Data.
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
CS102 Introduction to Computer Programming Chapter 7 Arrays.
1 Object-Oriented Programming Using C++ CLASS 27.
Lecture 18: Structured Data Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
1 Principles of Programming I Note Set #12. 2 Semester Overview Functions Character File I/O Arrays Pointers and Dynamic Memory Allocation Characters.
DCT1063 Programming 2 CHAPTER 5 ADVANCED DATA TYPE (part 1) Mohd Nazri Bin Ibrahim Faculty of Computer Media and Technology TATi University College
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 10: Records ( struct s)
CS1201: Programming Language 2 Structure By: Nouf Almunyif.
1 STRUCTURES AND POINTERS. 2 A VARIABLE OF THIS COMPOSITE TYPE CAN HAVE MORE THAN ONE VALUE, GROUPED TOGETHER TO DESCRIBE AN ENTITY. THE COMPONENTS OF.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
Starting Out with C++ 2nd Edition, by Tony Gaddis 1 Chapter 7 – Classes and Structured Data.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
Starting Out with C++, 3 rd Edition 1 Chapter 13 – Introduction to Classes.
1 Chapter 11 Structured Data. 2 Topics 10.1 Abstract Data Types 10.2 Combining Data into Structures 10.3 Accessing Structure Members 10.4 Initializing.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Structured Data and Classes Chapter 7. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Structured Data Chapter 11. Combining Data Into Structures Structure: C++ construct that allows multiple variables to be grouped together Format: struct.
Chapter 7 A Data Types – Structures Structures Structure: C++ construct that allows multiple variables to be grouped together Structure Declaration.
Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
1 Structured Data (Lecture 11) By: Dr. Norazah Yusof FSKSM, UTM.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Starting Out with C++, 3 rd Edition Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
1 1  Lecture 11 – Structured Data FTMK, UTeM – Sem /2014.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7. 12: Structures Starting Out with C++ Early Objects Eighth.
1 Class 19 Chapter 13 – Creating a class definition.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Chapter Structured Data 11. Combining Data into Structures 11.2.
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
Topic 4 Data Structures Program Development and Design Using C++, Third Edition.
Structured Data.
Structured Data Abstract data types (ADTs) are data types created by the programmer. ADTs have their own range (or domain) of data and their own set of.
11 Chapter Structured Data
CO1401 Program Design and Implementation
Chapter 7 – Arrays.
Structured Data (Lecture 07)
Chapter 1. Introduction to Computers and Programming
Chapter 11: Structured Data.
Data Types – Structures
DATA HANDLING.
Data Types – Structures
Starting Out with C++: From Control Structures through Objects
Chapter 11: Structured Data.
Standard Version of Starting Out with C++, 4th Edition
Structures, Unions, and Enumerations
Presentation transcript:

1 CS102 Introduction to Computer Programming Chapter 11 Structured Data

2 Topics for Discussion First Week Abstract Data Types Combining Data Into Structures Accessing structure Members Strings as Structure Members Initializing a Structure Arrays of structures Initializing a Structure Array Nested Structures Structures as Function Arguments Returning a Structure from a Function

3 Concept - An abstraction is a general model of something Abstraction An abstraction defines the general characteristics of an object –Dog - a highly variable carnivorous domesticated mammal. It captures the essence of all the objects that it defines without specifying details –The range of values The int data type is a number between and –The types of operations The int data type operators are +, -, *, /,, =, = =, !=

4 Abstract Data Types(ADT) The programmer decides what values are acceptable and the operations allowed Hours are the integers 1 through = 1 ADTs can be combined to form other ADTs Time is Hours, Minutes, Seconds Year is Months, Days, Time Concept - Abstract Data Types are Data Types created by the programmer

5 Combining Data Into Structures Arrays group information of the same data type together Parallel arrays can group information of different data types Structures create a data type that consists of a collection of other related data types Concept - C++ allows you to group several variables into a single item known as a structure. int Name [3]; int Empno [3]; float Wage[3]; struct Employee { int Empno; float Wage; }; //note the semicolon

6 The struct declaration The structure declaration does not define a variable. It creates a new data type. struct Employee { int Empno; float Wage; float Rate ; }; Concept - Structure Variables are made up of other variables known as members A variable of this new type is defined like other data types. Employee DeptHead; The variable DeptHead has the members: Empno Wage Rate

7 Defining ADT Variables Multiple variables can be defined with one statement Employee DeptHead, Manager, Engineer; Each variable is an instance of the type Employee –A variable is an instance of a structure that exits in memory –Each contains members as defined by the structure definition DeptHead: Empno Wage Rate Manager: Empno Wage Rate Engineer: Empno Wage Rate

8 Two steps to implementing structures: Create the structure declaration. This establishes the tag (or name) of the structure and a list of items that are members. Declare variables (or instances) of the structure and use them in the program to hold data.

9 Accessing structure Members The dot operator is used to specify a single member of a structure variable DeptHead.Empno = 345; Manager.Empno = 346; Engineer.Empno = 347; Concept - The dot operator (.) allows you to access structure members in a program The member name is similar to an array index used to access data in a structure variable. cout >>DeptHead.Empno; cout >> DeptHead.Wage; cout >> DeptHead.Rate; Note: The contents of a structure variable cannot be displayed by passing the entire variable to cout

10 Program 11-1 /* This program demonstrates the use of structures. #include struct PayRoll { int EmpNumber; // Employee number char Name[25]; // Employee's name float Hours; // Hours worked float PayRate; // Hourly Payrate float GrossPay; // Gross Pay }; void main(void) { PayRoll Employee; // Employee is a PayRoll structure cout << "Enter the employee's number: "; cin >> Employee.EmpNumber; cout << "Enter the employee's name: "; cin.ignore();// To skip the remaining // '\n' character cin.getline(Employee.Name, 25); cout << "How many hours did the employee work? "; cin >> Employee.Hours; cout << "What is the employee's hourly payrate? "; cin >> Employee.PayRate; Employee.GrossPay = Employee.Hours * Employee.PayRate; cout << "Here 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 Payrate: " << Employee.PayRate << endl; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Gross Pay: $" << Employee.GrossPay << endl; }

11 Program Output with Example Input Enter the employee's number: 489 [Enter] Enter the employee's name: Jill Smith [Enter] How many hours did the employee work? 40 [Enter] What is the employee's hourly payrate? 20 [Enter] Here is the employee's payroll data: Name: Jill Smith Number: 489 Hours worked: 40 Hourly Payrate: 20 Gross Pay: $800.00

12 Strings as Structure Members When a character array is a structure member, use the same string manipulation techniques with it as you would with any other character array. Concept - Manipulate strings stored in structure members just as you would any string.

13 Program 11-3 // This program uses a structure to hold someone's first, middle, and last name. #include struct Name { char First[15]; char Middle[15]; char Last[15]; char Full[45]; }; void main(void) { Name Person; cout << "Enter your first name: "; cin >> Person.First; cout << "Enter your middle name: "; cin >> Person.Middle; cout << "Enter your last name: "; cin >> Person.Last; strcpy(Person.Full, Person.First); strcat(Person.Full, " "); strcat(Person.Full, Person.Middle); strcat(Person.Full, " "); strcat(Person.Full, Person.Last); cout << "\nYour full name is " << Person.Full << endl; } Program Output Enter your first name: Josephine [Enter] Enter your middle name: Yvonne [Enter] Enter your last name: Smith [Enter] Your full name is Josephine Yvonne Smith

14 Displaying a Structure The contents of a structure variable cannot be displayed by passing the entire variable to cout. For example, assuming Employee is a PayRoll structure variable, the following statement will not work: cout << Employee << endl; //won’t work!

15 Program 11-2 // This program uses a structure to hold geometric data about a circle. #include #include // For the pow function struct Circle { float Radius; float Diameter; float Area; }; const float Pi = ; void main(void) { Circle C; cout << "Enter the diameter of a circle: "; cin >> C.Diameter; C.Radius = C.Diameter / 2; C.Area = Pi * pow(C.Radius, 2.0); cout << "The radius and area of the circle are:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Radius: " << C.Radius << endl; cout << "Area: " << C.Area << endl; } Program Output Enter the diameter of a circle: 10 [Enter] The radius and area of the circle are: Radius: 5 Area: 78.54

16 Arrays of structures Struct Bookinfo { char Title[50]; char Author[30]; char Publisher[25]; float Price; }; Bookinfo Booklist[20]; Concept - Arrays of structures can simplify some programming tasks For (int i=0; i <20; i++) { cout << Booklist[i].Title <<" "; cout << Booklist [i].Author <<" "; cout << Booklist [i]. Publisher <<" "; cout << Booklist [i].Price <<" "; cout <<endl; };

17 Program 11-5 /* This program stores, in an array of structures, the hours worked by 5 employees, and their hourly pay rates. (This is a modification of Program 7-12.)*/ #include struct PayInfo { int Hours;// Hours Worked float PayRate;// Hourly Pay Rate }; void main(void) { PayInfo Workers[5]; // Array of 5 structures cout << "Enter the hours worked by 5 employees and their\n"; cout << "hourly rates.\n"; for (int Index = 0; Index < 5; Index++) { cout << "Hours worked by employee #" << (Index + 1) << ": ";; cin >> Workers[Index].Hours; cout << "Hourly pay rate for employee #"; cout << (Index + 1) << ": "; cin >> Workers[Index].PayRate; } cout << "Here is the gross pay for each employee:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); for (Index = 0; Index < 5; Index++) { float Gross; Gross = Workers[Index].Hours * Workers[Index].PayRate; cout << "Employee #" << (Index + 1); cout << ": $" << Gross << endl; }

18 Program Output with Example Input Enter the hours worked by 5 employees and their hourly rates. Hours worked by employee #1: 10 [Enter] Hourly pay rate for employee #1: 9.75 [Enter] Hours worked by employee #2: 15 [Enter] Hourly pay rate for employee #2: 8.62 [Enter] Hours worked by employee #3: 20 [Enter] Hourly pay rate for employee #3: [Enter] Hours worked by employee #4: 40 [Enter] Hourly pay rate for employee #4: [Enter] Hours worked by employee #5: 40 [Enter] Hourly pay rate for employee #5: [Enter] Here is the gross pay for each employee: Employee #1: $97.50 Employee #2: $ Employee #3: $ Employee #4: $ Employee #5: $626.00

19 Initializing a Structure A structure variable may be declared with an initialization list. ( Not the structure declaration) The items of the initialization list must appear in the order the members appear. You can provide a partial initialization list. You can not skip items in the initialization list. Concept - The members of a structure may be initialized with starting values when the structure variable is declared.

20 Concept - A structure array can be initialized like any other array Bookinfo Booklist[5] = { {"C++","Gadis","Scott",60}, {"Visual Basic","Irvine ","Scott",50}, {"Java","Gittleman","Scott",40} }; Struct Bookinfo { char Title[50]; char Author[30]; char Publisher[25]; float Price; }; Initializing a Structure Array Partial initialization allowed No skipping elements

21 Nested Structures struct Costs { float Wholesale; float retail; }; struct Item { char PartNum [10]; char Desc[25]; Costs Pricing; }; Concept - It is possible for a structure variable to be a member of another structure. Item Widget = { "A500FR000L", "Wrench", };

22 Program 11-6 /*This program shows a structure with two nested structure members.*/ #include struct Date { int Month, Day, Year; }; struct Place { char Address[50]; char City[20]; char State[15]; char Zip[11]; }; struct EmpInfo { char Name[50]; int EmpNumber; Date BirthDate; Place Residence; }; void main(void) { EmpInfo Manager; // Ask for the manager's name and employee number cout << "Enter the manager's name: "; cin.getline(Manager.Name, 50); cout << "Enter the manager's employee number: "; cin >> Manager.EmpNumber; // Get the manager's birth date cout << "Now enter the manager's date-of- birth.\n"; cout << "Month (up to 2 digits): "; cin >> Manager.BirthDate.Month; cout << "Day (up to 2 digits): "; cin >> Manager.BirthDate.Day; cout << "Year (2 digits): "; cin >> Manager.BirthDate.Year; cin.get();// Eat the remaining newline character

23 Program 11-6 continues // Display the information just entered cout << "\nHere is the manager's information:\n"; cout << Manager.Name << endl; cout << "Employee number " << Manager.EmpNumber << endl; cout << "Date of Birth: "; cout << Manager.BirthDate.Month << "-"; cout << Manager.BirthDate.Day << "-"; cout << Manager.BirthDate.Year << endl; cout << "Place of residence:\n"; cout << Manager.Residence.Address << endl; cout << Manager.Residence.City << ", "; cout << Manager.Residence.State << " "; cout << Manager.Residence.Zip << endl; } // Get the manager's residence information cout << "Enter the manager's street address: "; cin.getline(Manager.Residence.Address, 50); cout << "City: "; cin.getline(Manager.Residence.City, 20); cout << "State: "; cin.getline(Manager.Residence.State, 15); cout << "Zip Code: "; cin.getline(Manager.Residence.Zip, 11);

24 Program Output with Example Input: Enter the manager's name: John Smith [Enter] Enter the manager's employee number: 789 [Enter] Now enter the manager's date-of-birth Month (up to 2 digits): 10 [Enter] Day (up to 2 digits): 14 [Enter] Year (2 digits): 65 [Enter] Enter the manager's street address: 190 Disk Drive [Enter] City: Redmond [Enter] State: WA [Enter] Zip Code: [Enter] Here is the manager's information: John Smith Employee number 789 Date of birth: Place of residence: 190 Disk Drive Redmond, WA 98052

25 Structures as Function Arguments Members of a structure variable can be passed to a function. The structure members must be defined before they can be referenced in a function prototype. A structure variable or member can be passed by value of by reference. Concept - Structure variables may be passed as arguments to functions

26 Figure 11-3

27 Program 11-7 // This program demonstrates a function that accepts // a structure variable as its argument. #include using namespace std; struct InvItem { int PartNum; char Description[50]; int OnHand; float Price; }; void ShowItem(InvItem);// Function prototype void main(void) { InvItem Part = {171, "Industrial Widget", 25, 150.0}; ShowItem(Part); } // Definition of function ShowItem. This function accepts an argument of the InvItem structure type. The contents of the structure is displayed. void ShowItem(InvItem Piece) { cout << precision(2); cout << fixed << showpoint; cout << "Part Number: " << Piece.PartNum << endl; cout << "Description: " << Piece.Description << endl; cout << "Units On Hand: " << Piece.OnHand << endl; cout << "Price: $" << Piece.Price << endl; } Program Output Part Number: 171 Description: Industrial Widget Units On Hand: 25 Price: $150.00

28 Program 11-8 /* This program has a function that uses a structure reference variable as its parameter.*/ #include struct InvItem { int PartNum;// Part number char Description[50]; // Item description int OnHand;// Units on hand float Price;// Unit price }; // Function Prototypes void GetItem(InvItem&); void ShowItem(InvItem) void main(void) { InvItem Part; GetItem(Part); ShowItem(Part); } // Definition of function GetItem. This function uses a structure reference variable as its parameter. It asks the user for information to store in the structure. void GetItem(InvItem &Piece) { cout << "Enter the part number: "; cin >> Piece.PartNum; cout << "Enter the part description: "; cin.get(); // Eat the remaining newline cin.getline(Piece.Description, 50); cout << "Enter the quantity on hand: "; cin >> Piece.OnHand; cout << "Enter the unit price: "; cin >> Piece.Price; }

29 Program 11-8 continues /* Definition of function ShowItem. This function accepts an argument of the InvItem structure type. The contents of the structure is displayed. */ void ShowItem(InvItem Piece) { cout << precision(2) << fixed << showpoint; cout << "Part Number: " << Piece.PartNum << endl; cout << "Description: " << Piece.Description << endl; cout << "Units On Hand: " << Piece.OnHand << endl; cout << "Price: $" << Piece.Price << endl; } Program Output Enter the part number: 800 [Enter] Enter the part description: Screwdriver [Enter] Enter the quantity on hand: 135 [Enter] Enter the unit price: 1.25 [Enter] Part Number: 800 Description: Screwdriver Units On Hand: 135 Price: $1.25

30 Constant Reference Parameters Sometimes structures can be quite large. Therefore, passing by value can decrease a program’s performance. But passing by reference can cause problems. Instead, pass by constant reference: void ShowItem(const InvItem &Piece) { cout.setf(ios::precision(2)|ios::fixed|ios::showpoint); cout << “Part Number: “ << piece.PartNum << endl; cout << “Price: $” << piece.Price << endl; }

31 Returning a Structure from a Function Allows a function to return multiple values The structure variable to be returned must be defined within the function Concept - A Structure may return a function struct rectangle { float length; float width; float area; }; rectangle getbox(void); void main (void) { rectangle box; box = getbox(); cout <<box.area; } rectangle getbox (void) { rectangle B; B.length =5; B.width=6; B.area = B.length*b.width; return B; }

32 Program 11-9 /* This program uses a function to return a structure. This is a modification of Program 11-2.*/ #include #include // For the pow function struct Circle // Circle structure declaration { float Radius; float Diameter; float Area; }; Circle GetInfo(void); // Function prototype const float Pi = ; // Constant for Pi void main(void) { Circle C; C = GetInfo(); C.Area = Pi * pow(C.Radius, 2.0); cout << "The radius and area of the circle are:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Radius: " << C.Radius << endl; cout << "Area: " << C.Area << endl; }

33 Program Continues Program Output Enter the diameter of a circle: 10 [Enter] The radius and area of the circle are: Radius: 5.00 Area: // Definition of function GetInfo. This function uses a local variable, Round, which is a Circle structure. The user enters the diameter of the circle, which is stored in Round.Diameter. The function then calculates the radius, which is stored in Round.Radius. Round is then returned from the function. Circle GetInfo(void) { Circle Round; cout << "Enter the diameter of a circle: "; cin >> Round.Diameter; Round.Radius = Round.Diameter / 2; return Round; }

34 Concept - You may take the address of a structure variable and create variables that are pointers to structures. Pointers to Structures A pointer to a structure is declared just like any other pointer variable The. has precedence over the * for indirecton C++ has a special structure pointer operator -> to dereference pointers Passing a structure pointer as an argument to a function gives the function access to the original structure

35 Pointers to Structures *CirPtr.Radius = 10; //incorrect way to access Radius because the dot operator has higher precedence Circle *CirPtr, PiePlate ; CirPtr = &PiePlate; (*CirPtr).Radius = 10; //correct access to Radius CirPtr->Radius = 10; //structure pointer operator, easier notation for dereferencing structure pointers

36 Program /* This program demonstrates a function that uses a pointer to a structure variable as a parameter.*/ #include struct Student { char Name[35]; int IdNum; int CrdHrs; float Gpa; }; // Function prototype void GetData(Student *); void main(void) { Student Freshman; cout << "Enter the following student data:\n"; GetData(&Freshman); cout << "\nHere is the student data you entered:\n"; cout.precision(2); // Now display the data stored in Freshman cout << "Name: " << Freshman.Name << endl; cout << "ID Number: " << Freshman.IdNum << endl; cout << "Credit Hours: " << Freshman.CrdHrs << endl; cout << "GPA: " << Freshman.Gpa << endl; }

37 Program continues /* Definition of function GetData. Uses a pointer to a Student structure variable. The user enters student information, which is stored in the variable.*/ void GetData(Student *S) { cout << "Student Name: "; cin.getline(S->Name, 35); cout << "Student ID Number: "; cin.ignore(); // Ignore the leftover newline cin >> S->IdNum; cout << "Credit Hours Enrolled: "; cin >> S->CrdHrs; cout << "Current GPA: "; cin >> S->Gpa; } Program Output Enter the following student data: Student Name: Frank Smith [Enter] Student ID Number: 4876 [Enter] Credit Hours Enrolled: 12 [Enter] Current GPA: 3.45 [Enter] Here is the student data you entered: Name: Frank Smith ID Number: 4876 Credit Hours: 12 GPA: 3.45

38 When to Use., When to Use ->, and When to Use *

39 Unions Unions conserve memory Only one member can be used at a time declared using the keyword union –Are like structures in all other respects Can contain arrays Can contain Functions Can be passed to and returned from a function Concept - A union is like a structure, except all the members occupy the same place in memory

40 Unions

41 Program // This program demonstrates a union. #include #include // For toupper union PaySource { short Hours; float Sales; }; void main(void) { PaySource Employee1; char PayType; float PayRate, GrossPay; cout.precision(2); cout.setf(ios::showpoint); cout << "This program calculates either hourly wages or\n"; cout << "sales commission.\n"; cout << "Enter H for hourly wages or C for commission: "; cin >> PayType; if (toupper(PayType) == 'H') { cout << "What is the hourly pay rate? "; cin >> PayRate; cout << "How many hours were worked? "; cin >> Employee1.Hours; GrossPay = Employee1.Hours * PayRate; cout << "Gross pay: $" << GrossPay << endl; }

42 Program continues else if (toupper(PayType) == 'C') { cout << "What are the total sales for this employee? "; cin >> Employee1.Sales; GrossPay = Employee1.Sales * 0.10; cout << "Gross pay: $" << GrossPay << endl; } else { cout << PayType << " is not a valid selection.\n"; } Program Output This program calculates either hourly wages or sales commission. Enter H for hourly wages or C for commission: C [Enter] What are the total sales for this employee? 5000 [Enter] Gross pay: $500.00

43 Concept - An anonymous union is a union with no name. Anonymous Unions The members of an anonymous union have names but the union has no name. Anonymous union declarations actually create the member variables in memory Members may be accessed without using the. operator

44 Program // This program demonstrates an anonymous union. #include #include // For toupper void main(void) { union// Anonymous union { short Hours; float Sales; }; char PayType; float PayRate, GrossPay; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "This program calculates either hourly wages or\n"; cout << "sales commission.\n"; cout << "Enter H for hourly wages or C for commission: "; cin >> PayType; if (toupper(PayType) == 'H') { cout << "What is the hourly pay rate? "; cin >> PayRate; cout << "How many hours were worked? "; cin >> Hours; // Anonymous union member GrossPay = Hours * PayRate; cout << "Gross pay: $" << GrossPay << endl; }

45 Program continues else if (toupper(PayType) == 'C') { cout << "What are the total sales for this employee? "; cin >> Sales; // Anonymous union member GrossPay = Sales * 0.10; cout << "Gross pay: $" << GrossPay << endl; } else { cout << PayType << " is not a valid selection.\n"; } Program Output This program calcualtes either hourly wages or sales commission. Enter H for hourly wages or C for commission: C [Enter] What are the total sales for the employee? [Enter] Gross pay: $

46 Linked Lists A link list is a series of structures that can grow or shrink in size as the program runs It is called linked because each structure contains a member that is a pointer to the next structure Structures in a linked list are called nodes Concept - Dynamically allocated structures may be linked together in memory to form a chain Data \0 Data Run and explain program 10.12

47 Variations of the linked List Doubly linked lists Circular linked lists Concept - There are many ways of linking dynamically allocated structures together Data \0 Data \0 Data