Lesson 11 Structured Data CS1 Lesson 11 -- John Cole1.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
C++ Statements represent the lowest-level building blocks of a program and it may be like:. A simple statement is a computation terminated by a semicolon.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Class Scope class Student { private: string id; string firstName, lastName; float gpa; public: void Read() { cin >> id >> firstName >> lastName >> gpa;
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Student Data Score First Name Last Name ID GPA DOB Phone... How to store student data in our programs? 1.
Starting Out with C++: Early Objects 5th Edition
1 Lecture 29 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter 7: Introduction to Classes and Objects
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
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.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Programmer Defined Structures (Records)
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 7: Introduction.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified.
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.
Triangle A polygon with three sides and three angles. A triangle can be names by its’ side lengths and angles. – Side lengths: isosceles, equilateral,
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.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.
1 Structured Data (Lecture 11) By: Dr. Norazah Yusof FSKSM, UTM.
CPS120: Introduction to Computer Science Lecture 15A Structures.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
CPS120: Introduction to Computer Science Data Structures.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
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.
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
1 Data Structures CSCI 132, Spring 2014 Lecture 2 Classes and Abstract Data Types Read Ch Read Style Guide (see course webpage)
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.
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.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++
Topic 4 Data Structures Program Development and Design Using C++, Third Edition.
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
Chapter 7: Introduction to Classes and Objects
11 Chapter Structured Data
Chapter 7: Introduction to Classes and Objects
Abstract Data Types Programmer-created data types that specify
Chapter 7: Introduction to Classes and Objects
Structured Data (Lecture 07)
Chapter 11: Structured Data.
Chapter 7: Introduction to Classes and Objects
Chapter 7: Introduction to Classes and Objects
Data Types – Structures
Data Types – Structures
Classes and Data Abstraction
Chapter 11: Structured Data.
CPS120: Introduction to Computer Science
Standard Version of Starting Out with C++, 4th Edition
Programming Fundamental
Presentation transcript:

Lesson 11 Structured Data CS1 Lesson John Cole1

Abstract Data Types A data type that specifies –values that can be stored –operations that can be done on the values User of an abstract data type does not need to know the implementation of the data type, e.g., how the data is stored ADTs are created by programmers CS1 Lesson John Cole2

Abstraction and Data Types Abstraction: a definition that captures general characteristics without details –Ex: An abstract triangle is a 3-sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type defines the values that can be stored in a variable and the operations that can be performed on it CS1 Lesson John Cole3

Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together General Format: struct { type1 field1; type2 field2;... }; CS1 Lesson John Cole4

Example struct Declaration CS1 Lesson John Cole5 struct Student { int studentID; string name; short yearInSchool; double gpa; };// Semicolon required structure tag structure members

struct Declaration Notes Must have ; after closing } struct names commonly begin with uppercase letter Multiple fields of same type can be in comma-separated list: string name, address; CS1 Lesson John Cole6

Defining Structure Variables struct declaration does not allocate memory or create variables To define variables, use structure tag as type name: Student bill; CS1 Lesson John Cole7 studentID name yearInSchool gpa bill

Accessing Structure Members Use the dot (.) operator to refer to members of struct variables: cin >> stu1.studentID; getline(cin, stu1.name); stu1.gpa = 3.75; Member variables can be used in any manner appropriate for their data type CS1 Lesson John Cole8

Example: Fill student struct struct Student { string studentID; string firstName; string lastName; int credits; string major; }; CS1 Lesson John Cole9

Example, continued Student std; cout << "Student information\nEnter student ID: "; cin >> std.studentID; cin.ignore(); cout << "Enter First Name: "; cin >> std.firstName; cin.ignore(); cout << "Enter Last Name: "; cin >> std.lastName; cin.ignore(); cout << "Enter Major: "; cin >> std.major; cin.ignore(); cout << "Enter credits earned: "; cin >> std.credits; CS1 Lesson John Cole10

Displaying a struct Variable To display the contents of a struct variable, must display each field separately, using the dot operator: cout > "First name: " << bob.firstName << endl << "Last name: " << bob.lastName << endl; CS1 Lesson John Cole11

Comparing struct Variables Cannot compare struct variables directly: if (bill == william) // won ’ t work Instead, must compare on a field basis: if (bill.studentID == william.studentID)... CS1 Lesson John Cole12

Initializing a Structure A struct variable can be initialized when defined: Student s = {11465, "Joan", 2, 3.75}; Can also be initialized member-by- member after definition: s.name = "Joan"; s.gpa = 3.75; CS1 Lesson John Cole13

Initializing a Structure May initialize only some members: Student bill = {14579}; Cannot skip over members: Student s = {1234, "John",, 2.83}; // illegal Cannot initialize in the structure declaration, since this does not allocate memory CS1 Lesson John Cole14

Arrays of Structures Structures can be defined in arrays Can be used in place of parallel arrays const int NUM_STUDENTS = 20; Student stuList[NUM_STUDENTS]; Individual structures accessible using subscript notation Fields within structures accessible using dot notation: cout << stuList[5].studentID; CS1 Lesson John Cole15

Nested Structures A structure can contain another structure as a member: struct PersonInfo { string name, address, city; }; struct Student {int studentID; PersonInfo pData; short yearInSchool; double gpa; }; CS1 Lesson John Cole16

Members of Nested Structures Use the dot operator multiple times to refer to fields of nested structures: Student s; s.pData.name = "Joanne"; s.pData.city = "Tulsa"; CS1 Lesson John Cole17

Structures as Function Arguments May pass members of struct variables to functions: computeGPA(stu.gpa); May pass entire struct variables to functions: showData(stu); Can use reference parameter if function needs to modify contents of structure variable CS1 Lesson John Cole18

Structures as Function Arguments Using value parameter for structure can slow down a program, waste space Using a reference parameter will speed up program, but function may change data in structure Using a const reference parameter allows read-only access to reference parameter, does not waste space, speed CS1 Lesson John Cole19

Returning a Structure from a Function A function can return a struct : Student getStudentData(); // prototype stu1 = getStudentData(); // call A function must define a local structure –for internal use –for use with return statement CS1 Lesson John Cole20

Pointers to Structures A structure variable has an address Pointers to structures are variables that can hold the address of a structure: Student *stuPtr; Can use & operator to assign address: stuPtr = & stu1; Structure pointer can be a function parameter CS1 Lesson John Cole21

Accessing Structure Members via Pointer Variables Must use () to dereference pointer variable, not field within structure: cout << (*stuPtr).studentID; Can use structure pointer operator to eliminate () and use clearer notation: cout studentID; CS1 Lesson John Cole22

Unions Similar to a struct, but – all members share a single memory location, and – only one member of the union can be used at a time Declared using union, otherwise the same as struct Variables defined as for struct variables CS1 Lesson John Cole23

Unions In order to form a more perfect union… union charint { int x; char c[4]; }; The int and the char array both occupy the same 4 bytes of memory. CS1 Lesson John Cole24

Unions charint u; u.c[0] = 'a'; u.c[1] = 'b'; u.c[2] = 'c'; u.c[3] = 0; charint *ptrU = &u; u.x = (65*256) + 66; CS1 Lesson John Cole25

Anonymous Union A union without a union tag: union {... }; Must use static if declared outside of a function Allocates memory at declaration time Can refer to members directly without dot operator Uses only one memory location, saves space CS1 Lesson John Cole26

Enumerated Data Types An enumerated data type is a programmer-defined data type. It consists of values known as enumerators, which represent integer constants. CS1 Lesson John Cole27

Enumerated Data Types Example: enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; The identifiers MONDAY, TUESDAY, WEDNESDAY, THURSDAY, and FRIDAY, which are listed inside the braces, are enumerators. They represent the values that belong to the Day data type. CS1 Lesson John Cole28

Enumerated Data Types Note that the enumerators are not strings, so they aren’t enclosed in quotes. They are identifiers. Once you have created an enumerated data type in your program, you can define variables of that type. Example: Day workDay; This statement defines workDay as a variable of the Day type. CS1 Lesson John Cole29

Enumerated Data Types We may assign any of the enumerators MONDAY, TUESDAY, WEDNESDAY, THURSDAY, or FRIDAY to a variable of the Day type. Example: workDay = WEDNESDAY; CS1 Lesson John Cole30

Enumerated Data Types So, what is an enumerator? Think of it as an integer named constant Internally, the compiler assigns integer values to the enumerators, beginning at 0. CS1 Lesson John Cole31

Enumerated Data Types enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; CS1 Lesson John Cole32 In memory... MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4

Enumerated Data Types Using the Day declaration, the following code... cout << MONDAY << " " << WEDNESDAY << " “ << FRIDAY << endl;...will produce this output: CS1 Lesson John Cole33

Assigning an integer to an enum Variable You cannot directly assign an integer value to an enum variable. This will not work: workDay = 3;// Error! Instead, you must cast the integer: workDay = static_cast (3); CS1 Lesson John Cole34

Assigning an Enumerator to an int Variable You CAN assign an enumerator to an int variable. For example: int x; x = THURSDAY; This code assigns 3 to x. CS1 Lesson John Cole35

Comparing Enumerator Values Enumerator values can be compared using the relational operators. For example, using the Day data type the following code will display the message "Friday is greater than Monday.“ if (FRIDAY > MONDAY) { cout << "Friday is greater " << "than Monday.\n"; } CS1 Lesson John Cole36

Enumerated Data Types This program shows enumerators used to control a loop: // Get the sales for each day. for (index = MONDAY; index > sales[index]; } CS1 Lesson John Cole37

Anonymous Enumerated Types An anonymous enumerated type is simply one that does not have a name. For example, in Program we could have declared the enumerated type as: enum { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; CS1 Lesson John Cole38

Using Math Operators with enum Variables You can run into problems when trying to perform math operations with enum variables. For example: Day day1, day2; // Define two Day variables. day1 = TUESDAY; // Assign TUESDAY to day1. day2 = day1 + 1;// ERROR! Will not work! The third statement will not work because the expression day1 + 1 results in the integer value 2, and you cannot store an int in an enum variable. CS1 Lesson John Cole39

Using Math Operators with enum Variables You can fix this by using a cast to explicitly convert the result to Day, as shown here: // This will work. day2 = static_cast (day1 + 1); CS1 Lesson John Cole40

Using an enum Variable as an Array Index Because enumerators are stored in memory as integers, you can use them as array subscripts. For example: enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; const int NUM_DAYS = 5; double sales[NUM_DAYS]; sales[MONDAY] = ; sales[TUESDAY] = ; sales[WEDNESDAY] = ; sales[THURSDAY] = ; sales[FRIDAY] = ; CS1 Lesson John Cole41

Using an enum Variable as an Array Index Remember, though, you cannot use the ++ operator on an enum variable. So, the following loop will NOT work. Day workDay; // Define a Day variable // ERROR!!! This code will NOT work. for (workDay = MONDAY; workDay <= FRIDAY; workDay++) { cout << "Enter the sales for day " << workDay << ": "; cin >> sales[workDay]; } CS1 Lesson John Cole42

Using an enum Variable as an Array Index You must rewrite the loop’s update expression using a cast instead of ++: for (workDay = MONDAY; workDay <= FRIDAY; workDay = static_cast (workDay + 1)) { cout << "Enter the sales for day " << workDay << ": "; cin >> sales[workDay]; } CS1 Lesson John Cole43

Enumerators Must Be Unique Within the same Scope Enumerators must be unique within the same scope. For example, an error will result if both of the following enumerated types are declared within the same scope: CS1 Lesson John Cole44 enum Presidents { MCKINLEY, ROOSEVELT, TAFT }; enum VicePresidents { ROOSEVELT, FAIRBANKS, SHERMAN }; ROOSEVELT is declared twice.

Declaring the Type and Defining the Variables in One Statement You can declare an enumerated data type and define one or more variables of the type in the same statement. For example: CS1 Lesson John Cole45 enum Car { PORSCHE, FERRARI, JAGUAR } sportsCar; This code declares the Car data type and defines a variable named sportsCar.