Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 18: Structured Data Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.

Similar presentations


Presentation on theme: "Lecture 18: Structured Data Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220."— Presentation transcript:

1 Lecture 18: Structured Data Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220

2 Abstract Data Types Concept: Abstract data types (ADTs) are data types created by the programmer They have their own range (or domain) of data and their own sets of operations that may be performed on them

3 Abstraction A general model of something Includes only the general characteristics Example: a dog captures the essence without specifying details However, a real life dog is not abstract, it is concrete Example: poodle

4 Data types C++ has primitive data types bool, char, unsigned char, short int int, long int, unsigned short int, unsigned int unsigned long int, float, double, long double A data type defines what a variable can hold and its range Data types also define what operations can be performed on them + - * / > = <= == != int x = 1; int is the abstract data type x is the concrete occurrence

5 Abstract data types Data type created by the programmer Composed of one or more primitive data types Programmer decides what values are acceptable for the data type, as well as what operations may be performed on the data type

6 Combining Data into Structures C++ allows you to group several variable together into a single item know as a structure struct tag { variable declaration; // more declarations, etc. }; const int SIZE = 25; // array size struct PayRoll { int empNumber; // Employee number char name[SIZE]; // Employee’s name double hours; // Hours worked double payRate; // Hourly pay rate double grossPay; // Gross Pay };

7 Tips Semicolon (;) is needed after the closing curly bracket of the structure declaration Name of the structure tag begins with an uppercase letter (convention used in the book) You can declare variables of the same type on a single line as before This does not define a variable, simply tells the compiler what a PayRoll structure is made of This defines a variable of type PayRoll PayRoll deptHead;

8 Accessing structure members Concept: The dot operator (.) allows you to access structure members in a program deptHead.empNumber = 475; cout << deptHead.name << endl; This however, does not work! cout << deptHead << endl;

9 // This program demonstrates the use of structures. #include using namespace std; const int SIZE = 25; // Array size struct PayRoll { int empNumber; // Employee number char name[SIZE]; // Employee's name double hours; // Hours worked double payRate; // Hourly payRate double grossPay; // Gross Pay }; int main() { PayRoll employee; // employee is a PayRoll structure. // Get the employee's number. cout << "Enter the employee's number: "; cin >> employee.empNumber; // Get the employee's name. cout << "Enter the employee's name: "; cin.ignore(); // To skip the remaining '\n' character cin.getline(employee.name, SIZE); // Get the hours worked by the employee. cout << "How many hours did the employee work? "; cin >> employee.hours; // Get the employee's hourly pay rate. cout << "What is the employee's hourly payRate? "; cin >> employee.payRate; // Calculate the employee's gross pay. employee.grossPay = employee.hours * employee.payRate; // Display the employee data. 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 << fixed << showpoint << setprecision(2); cout << "Gross Pay: $" << employee.grossPay << endl; return 0; }

10 // This program stores data about a circle in a structure. #include #include // For the pow function #include using namespace std; // Constant for Pi. const double PI = 3.14159; // Structure declaration struct Circle { double radius; // A circle's radius double diameter; // A circle's diameter double area; // A circle's area }; int main() { Circle c; // Define a structure variable // Get the circle's diameter. cout << "Enter the diameter of a circle: "; cin >> c.diameter; // Calculate the circle's radius. c.radius = c.diameter / 2; // Calculate the circle's area. c.area = PI * pow(c.radius, 2.0); // Display the circle data. cout << fixed << showpoint << setprecision(2); cout << "The radius and area of the circle are:\n"; cout << "Radius: " << c.radius << endl; cout << "Area: " << c.area << endl; return 0; }

11 Comparing Structure Values Just like arrays, we cannot perform comparison operations directly on structure variables if (circle1 == circle2) // Error! if (circle1.radius == circle2.radius && circle1.diameter == circle2.diameter && circle1.area = circle2.area)

12 Strings as structure members When a character array is a structure member, you can use the same string manipulation techniques with it as you would any other character array.

13 // This program uses a structure to hold someone's first, // middle, and last name. #include using namespace std; // Constants for array lengths const int LENGTH = 15; const int FULL_LENGTH = 45; struct Name { char first[LENGTH]; // To hold the first name char middle[LENGTH]; // To hold the middle name char last[LENGTH]; // To hold the last name char full[FULL_LENGTH]; // To hold the full name }; int main() { // personName is a Name structure variable Name personName; // Get the first name. cout << "Enter your first name: "; cin >> personName.first; // Get the middle name. cout << "Enter your middle name: "; cin >> personName.middle; // Get the last name. cout << "Enter your last name: "; cin >> personName.last; // Assemble the full name. strcpy(personName.full, personName.first); strcat(personName.full, " "); strcat(personName.full, personName.middle); strcat(personName.full, " "); strcat(personName.full, personName.last); // Display the full name. cout << "\nYour full name is " << personName.full << endl; return 0; }

14 Initializing a structure Concept: The members of a structure variable may be initialized with starting values when the structure variable is defined No Skipping! struct CityInfo { char cityName[30]; char state[3]; long population; int distance; }; CityInfo location = {“Asheville”, “NC”, 50000, 28}; CityInfo location = {“Asheville”, “NC”}; CityInfo location = {“Asheville”, “NC”, 50000};

15 // This program demonstrates partially initialized // structure variables. #include using namespace std; const int LENGTH = 25; // Array size struct EmployeePay { char name[LENGTH]; // Employee name int empNum; // Employee number double payRate; // Hourly pay rate double hours; // Hours worked double grossPay; // Gross pay }; int main() { EmployeePay employee1 = {"Betty Ross", 141, 18.75}; EmployeePay employee2 = {"Jill Sandburg", 142, 17.50}; cout << fixed << showpoint << setprecision(2); // Calculate pay for employee1 cout << "Name: " << employee1.name << endl; cout << "Employee Number: " << employee1.empNum << endl; cout << "Enter the hours worked by this employee: "; cin >> employee1.hours; employee1.grossPay = employee1.hours * employee1.payRate; cout << "Gross Pay: " << employee1.grossPay << endl << endl; // Calculate pay for employee2 cout << "Name: " << employee2.name << endl; cout << "Employee Number: " << employee2.empNum << endl; cout << "Enter the hours worked by this employee: "; cin >> employee2.hours; employee2.grossPay = employee2.hours * employee2.payRate; cout << "Gross Pay: " << employee2.grossPay << endl; return 0; }

16 Arrays of Structures Concept: Arrays of structures simply some programming tasks struct BookInfo { char title[50]; char author[30]; char publisher[25]; double price; }; BookInfo bookList[20]; cout << bookList[5].title; cout << bookList[10].title[0]; for ( int index = 0; index < 20; index++) { cout << bookList[index].title; } // This program uses an array of structures. #include using namespace std; struct PayInfo { int hours; // Hours Worked double payRate; // Hourly Pay Rate }; int main() { const int NUM_WORKERS = 3; // Number of workers PayInfo workers[NUM_WORKERS]; // Array of structures int index; // Loop counter // Get employee pay data. cout << "Enter the hours worked by " << NUM_WORKERS << " employees and their hourly rates.\n"; for (index = 0; index < NUM_WORKERS; index++) { // Get the hours worked by an employee. cout << "Hours worked by employee #" << (index + 1); cout << ": "; cin >> workers[index].hours; // Get the employee's hourly pay rate. cout << "Hourly pay rate for employee #"; cout << (index + 1) << ": "; cin >> workers[index].payRate; cout << endl; } // Display each employee's gross pay. cout << "Here is the gross pay for each employee:\n"; cout << fixed << showpoint << setprecision(2); for (index = 0; index < NUM_WORKERS; index++) { double gross; gross = workers[index].hours * workers[index].payRate; cout << "Employee #" << (index + 1); cout << ": $" << gross << endl; } return 0; }

17 Initializing a Structure Array PayInfo workers[NUM_WORKERS] = { {10, 9.75}, {15, 8.62}, {20, 10.5}, {40, 15.65} }

18 Nested Structures Concept: It is possible for a structure variable to be a member of another structure struct Costs { double wholesale; double retail; }; struct Item { char partNum[10]; char description[25]; Costs pricing; }

19 // This program uses nested structures. #include using namespace std; // Constants for char array sizes const int ADDR_LENGTH = 50; // Address length const int CITY_LENGTH = 20; // City length const int STATE_LENGTH = 15; // State length const int ZIP_LENGTH = 11; // ZIP code length const int NAME_LENGTH = 50; // Name length // The Date structure holds data about a date. struct Date { int month; int day; int year; }; // The Place structure holds a physical address. struct Place { char address[ADDR_LENGTH]; char city[CITY_LENGTH]; char state[STATE_LENGTH]; char zip[ZIP_LENGTH]; }; // The EmployeeInfo structure holds an employee's data. struct EmployeeInfo { char name[NAME_LENGTH]; int employeeNumber; Date birthDate; // Nested structure Place residence; // Nested structure }; int main() { // Define a structure variable to hold info about the manager. EmployeeInfo manager; // Get the manager's name and employee number cout << "Enter the manager's name: "; cin.getline(manager.name, NAME_LENGTH); cout << "Enter the manager's employee number: "; cin >> manager.employeeNumber; // 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.ignore(); // Skip the remaining newline character // Get the manager's residence information cout << "Enter the manager's street address: "; cin.getline(manager.residence.address, ADDR_LENGTH); cout << "City: "; cin.getline(manager.residence.city, CITY_LENGTH); cout << "State: "; cin.getline(manager.residence.state, STATE_LENGTH); cout << "ZIP Code: "; cin.getline(manager.residence.zip, ZIP_LENGTH); // Display the information just entered cout << "\nHere is the manager's information:\n"; cout << manager.name << endl; cout << "Employee number " << manager.employeeNumber << 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; return 0; }

20 Structures as function arguments, and function returns Concept: Structure variables may be passed as arguments to functions Concept: A function may return a structure

21 // This program has functions that accept structure variables // as arguments. #include using namespace std; const int DESC_SIZE = 50; // Array size struct InventoryItem { int partNum; // Part number char description[DESC_SIZE]; // Item description int onHand; // Units on hand double price; // Unit price }; // Function Prototypes void getItem(InventoryItem&); // Argument passed by reference void showItem(InventoryItem); // Argument passed by value int main() { InventoryItem part; getItem(part); showItem(part); return 0; } //*********************************************************** // 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(InventoryItem &p) // Uses a reference parameter { // Get the part number. cout << "Enter the part number: "; cin >> p.partNum; // Get the part description. cout << "Enter the part description: "; cin.ignore(); // Ignore the remaining newline character cin.getline(p.description, DESC_SIZE); // Get the quantity on hand. cout << "Enter the quantity on hand: "; cin >> p.onHand; // Get the unit price. cout << "Enter the unit price: "; cin >> p.price; } //*********************************************************** // Definition of function showItem. This function accepts * // an argument of the InventoryItem structure type. The * // contents of the structure is displayed. * //*********************************************************** void showItem(InventoryItem p) { cout << fixed << showpoint << setprecision(2); cout << "Part Number: " << p.partNum << endl; cout << "Description: " << p.description << endl; cout << "Units On Hand: " << p.onHand << endl; cout << "Price: $" << p.price << endl; }

22 // This program uses a function to return a structure. This // is a modification of Program 11-2. #include #include // For the pow function using namespace std; // Constant for Pi. const double PI = 3.14159; // Structure declaration struct Circle { double radius; // A circle's radius double diameter; // A circle's diameter double area; // A circle's area }; // Function prototype Circle getInfo(); int main() { Circle c; // Define a structure variable // Get data about the circle. c = getInfo(); // Calculate the circle's area. c.area = PI * pow(c.radius, 2.0); // Display the circle data. cout << "The radius and area of the circle are:\n"; cout << fixed << setprecision(2); cout << "Radius: " << c.radius << endl; cout << "Area: " << c.area << endl; return 0; } //*************************************************************** // Definition of function getInfo. This function uses a local * // variable, tempCircle, which is a circle structure. The user * // enters the diameter of the circle, which is stored in * // tempCircle.diameter. The function then calculates the radius * // which is stored in tempCircle.radius. tempCircle is then * // returned from the function. * //*************************************************************** Circle getInfo() { Circle tempCircle; // Temporary structure variable // Store circle data in the temporary variable. cout << "Enter the diameter of a circle: "; cin >> tempCircle.diameter; tempCircle.radius = tempCircle.diameter / 2.0; // Return the temporary variable. return tempCircle; }


Download ppt "Lecture 18: Structured Data Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220."

Similar presentations


Ads by Google