Structured Data and Classes

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
1 Programming Structures COMP102 Prog. Fundamentals, Structures / Slide 2 2 Structures l A Structure is a collection of related data items, possibly.
Chapter 7: User-Defined Functions II
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Starting Out with C++: Early Objects 5th Edition
Introduction to C Programming CE Lecture 10 Data Structures typedef and struct.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 10: Records ( struct s)
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Arrays Chapter 8.
Learners Support Publications Classes and Objects.
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 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.
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.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
+ 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.
C++ Class. © 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1 Isolated tasks: the implementation of task T does not.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Weekly C-minar Week 0. Today: Steps of the compile Basic inclusion/syntax rules Low-cost containment Debugging.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
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.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
C Programming 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.
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++
Chapter 7: Introduction to Classes and Objects
11 Chapter Structured Data
Abstract Data Types Programmer-created data types that specify
Chapter 7: Introduction to Classes and Objects
Chapter 11: Structured Data.
Chapter 7: Introduction to Classes and Objects
Chapter 7: Introduction to Classes and Objects
Data Types – Structures
Data Types – Structures
C Structures, Unions, Bit Manipulations and Enumerations
Introduction to Classes
Chapter 11: Structured Data.
Classes and Objects.
Standard Version of Starting Out with C++, 4th Edition
Programming Fundamental
Presentation transcript:

Structured Data and Classes

Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure Declaration Format: struct structure name { type1 field1; type2 field2; … typen fieldn; };

Example struct Declaration struct Student { int studentID; string name; short year; double gpa; }; structure tag structure members Notice the required ;

struct examples Example: The “StudentGrade” structure has 5 members of struct StudentInfo{ int Id; int age; char Gender; double CGA; }; struct StudentGrade{ char Name[15]; char Course[9]; int Lab[5]; int Homework[3]; int Exam[2]; The “StudentInfo” structure has 4 members of different types. The “StudentGrade” structure has 5 members of different array types.

struct examples Example: The “StudentRecord” structure has 4 struct BankAccount{ char Name[15]; int AcountNo[10]; double balance; Date Birthday; }; struct StudentRecord{ int Id; char Dept[5]; char Gender; The “BankAcount” structure has simple, array and structure types as members. The “StudentRecord” structure has 4 members.

struct Declaration Notes struct names commonly begin with an uppercase letter Multiple fields of same type can be in a comma-separated list string name, address;

Defining Structure Variables struct declaration does not allocate memory or create variables To define variables, use structure tag as type name Student s1; studentID name year gpa s1

Example: structures struct date { int month; int day; int year; }; Defines type struct date, with 3 fields of type int The names of the fields are local in the context of the structure. A struct declaration defines a type: if not followed by a list of variables it reserves no storage; it merely describes a template or shape of a structure. Defines 3 variables of type struct date struct date today, purchaseDate; today.year = 2004; today.month = 10; today.day = 5; Accesses fields of a variable of type struct date A member of a particular structure is referred to in an expression by a construction of the form structurename.member

Structure definition To define a structure for student’s information typedef struct { char [30] name; int age; } student; Student s1, s2;

Structure using When we use the structure data as S1.age = 21; Strcpy(s1.name, “mohamed”); Strcpy(s2.name, “ahmed”);

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

Displaying struct Members To display the contents of a struct variable, you must display each field separately, using the dot operator Wrong: cout << s1; // won’t work! Correct: cout << s1.studentID << endl; cout << s1.name << endl; cout << s1.year << endl; cout << s1.gpa; See pr7-01.cpp and pr7-02.cpp

Initializing a Structure Cannot initialize members in the structure declaration, because no memory has been allocated yet struct Student // Illegal { // initialization int studentID = 1145; string name = "Alex"; short year = 1; float gpa = 2.95; };

Example Write a program which accepts from the user via the keyboards, and the following data items: it_number – integer value, name – string, up to 20 characters, amount – integer value. Your program will store this data for 3 persons and display each record is proceeded by the record number.

Comparing struct Variables Cannot compare struct variables directly: if (stu1 == stu2) // won’t work Instead, must compare on a member basis: if (stu1.studentID == stu2.studentID)

Initializing a Structure (continued) Structure members are initialized at the time a structure variable is created Can initialize a structure variable’s members with either an initialization list a constructor

Using an Initialization List An initialization list is an ordered set of values, separated by commas and contained in { }, that provides initial values for a set of data members {12, 6, 3} // initialization list // with 3 values

More on Initialization Lists Order of list elements matters: First value initializes first data member, second value initializes second data member, etc. Elements of an initialization list can be constants, variables, or expressions {12, W, L/W + 1} // initialization list // with 3 items

Initialization List Example Structure Declaration Structure Variable struct Dimensions { int length, width, height; }; Dimensions box = {12,6,3}; box length 12 width 6 height 3

Partial Initialization Can initialize just some members, but cannot skip over members Dimensions box1 = {12,6}; //OK Dimensions box2 = {12,,3}; //illegal

Problems with Initialization List Can’t omit a value for a member without omitting values for all following members Does not work on most modern compilers if the structure contains any string objects Will, however, work with C-string members

Omit () when no arguments are used Examples //Create a box with all dimensions given Dimensions box4(12, 6, 3); //Create a box using default value 1 for //height Dimensions box5(12, 6); //Create a box using all default values Dimensions box6; See pr7-03.cpp Omit () when no arguments are used

Example Write a car struct that has the following fields: YearModel (int), Make (string), and Speed (int). The program has function assign_data ( ) accelerate ( ) which add 5 to the speed each time it is called, break () which subtract 5 from speed each time it is called, and display () to print out the car’s information.

Nested Structures A structure can have another structure as a member. struct PersonInfo { string name, address, city; }; struct Student { int studentID; PersonInfo pData; short year; double gpa;

Members of Nested Structures Use the dot operator multiple times to dereference fields of nested structures Student s5; s5.pData.name = "Joanne"; s5.pData.city = "Tulsa"; See pr7-04.cpp

Example Create a structTime that contains data members, hour, minute, second to store the time value, provide a function that sets hour, minute, second to zero, provide three function for converting time to ( 24 hour ) and another one for converting time to ( 12 hour ) and a function that sets the time to a certain value specified by three parameters

Arrays of Structures Structures can be defined in arrays Structures can be used in place of parallel arrays Student stuList[20]; Individual structures accessible using subscript notation Fields within structures accessible using dot notation: cout << stuList[5].studentID;

Structures as Function Arguments May pass members of struct variables to functions computeGPA(s1.gpa); May pass entire struct variables to functions showData(s5); Can use reference parameter if function needs to modify contents of structure variable

Example Coffee shop needs a program to computerize its inventory. The data will be Coffee name, price, and amount in stock, sell by year. The function on coffee are: prepare to enter stock, Display coffee data, change price, add stock (add new batch), sell coffee, remove old stock (check sell by year).

Notes on Passing Structures Using a value parameter for structure can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the structure To save space and time, while protecting structure data that should not be changed, use a const reference parameter void showData(const Student &s) // header See pr7-05.cpp

Returning a Structure from a Function Function can return a struct Student getStuData(); // prototype s1 = getStuData(); // call Function must define a local structure for internal use to use with return statement

Returning a Structure Example Student getStuData() { Student s; // local variable cin >> s.studentID; cin.ignore(); getline(cin, s.pData.name); getline(cin, s.pData.address); getline(cin, s.pData.city); cin >> s.year; cin >> s.gpa; return s; } See pr7-06.cpp

Example Design a struct named BankAccount with data: balance, number of deposits this month, number of withdrawals, annual interest rate, and monthly service charges. The program has functions: Deposit (amount) {add amount to balance and increment number of deposit by one}, Withdraw (amount) {subtract amount from balance and increment number of withdrawals by one}, CalcInterest() { update balance by amount = balance * (annual interest rate /12)}, and MonthlyPocess() {subtract the monthly service charge from balance, set number of deposit, number of withdrawals and monthly service charges to zero}.

Pointers to Structures A structure variable has an address Pointers to structures are variables that can hold the address of a structure: Student * stuPtr, stu1; Use the & operator to assign an address: stuPtr = & stu1; A structure pointer can be a function parameter

Accessing Structure Members via Pointer Variables Use () to dereference the pointer variable, not the field within the structure: cout << (*stuPtr).studentID; You can use the structure pointer operator ( -> ), a.k.a arrow operator to eliminate use of(*). cout << stuPtr -> studentID;

Pointers to Structures You may take the address of a structure variable and create variables that are pointers to structures. Circle *cirPtr; // cirPtr is a pointer to a Circle CirPtr = &piePlate; *cirPtr.radius = 10; // incorrect way to access Radius because the dot operator // has higher precedence than the indirection operator (*cirPtr).radius = 10; //correct access to Radius cirPtr -> radius = 10; // structure pointer operator ( -> ), easier notation for // dereferencing structure pointers

Example Write a complete program to Define a person struct with members: ID, name, address, and telephone number. The functions are change_data( ), get_data( ), and display_data( ). Declare record table with size N and provide the user to fill the table with data. Allow the user to enter certain ID for the Main function to display the corresponding person's name, address, and telephone number.

Linked List

Unions Similar to a struct, but Declared using key word union all members share a single memory location (which saves space) only 1 member of the union can be used at a time Declared using key word union Otherwise the same as struct Variables defined and accessed like struct variables

Example union Declaration union WageInfo { double hourlyRate; float annualSalary; }; union tag union members See pr7-07.cpp Notice the required ;

Anonymous Union A union without a tag: With no tag you cannot create additional union variables of this type later Allocates memory at declaration time Refer to members directly without dot operator See pr7-08.cpp

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

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. The enumerators are named constants.

Enumerated Data Types 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.

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;

Enumerated Data Types enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; 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: 0 2 4

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.

Enumerated Data Types Program 11-13 shows enumerators used to control a loop: // Get the sales for each day. for (index = MONDAY; index <= FRIDAY; index++) { cout << "Enter the sales for day " << index << ": "; cin >> sales[index]; } // Would not work if index was an enumerated type

Using an enum Variable to Step through an Array's Elements 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] = 1525.00; sales[TUESDAY] = 1896.50; sales[WEDNESDAY] = 1975.63; sales[THURSDAY] = 1678.33; sales[FRIDAY] = 1498.52;

STRUCT, TYPEDEF, ENUM & UNION You cannot use the typedef specifier inside a function definition. When declaring a local-scope identifier by the same name as a typedef, or when declaring a member of a structure or union in the same scope or in an inner scope, the type specifier must be specified. For example, typedef float TestType;   int main(void) { ...  } // function scope (local) int MyFunct(int) {       // same name with typedef, it is OK       int TestType; } www.tenouk.com, ©

STRUCT, TYPEDEF, ENUM & UNION Names for structure types are often defined with typedef to create shorter and simpler type name. For example, the following statements, typedef  struct Card MyCard; typedef unsigned short USHORT; Defines the new type name MyCard as a synonym for type struct Card and USHORT as a synonym for type unsigned short. Programmers usually use typedef to define a structure (also union, enum and class) type so a structure tag is not required. For example, the following definition. typedef struct{       char  *face;       char  *suit; } MyCard;

Creating Header File and File Re-inclusion Issue It is a normal practice to separate structure, function, constants, macros, types and similar definitions and declarations in a separate header file(s). Then, those definitions can be included in main() using the include directive (#include). It is for reusability and packaging and to be shared between several source files. Include files are also useful for incorporating declarations of external variables and complex data types. You need to define and name the types only once in an include file created for that purpose. The #include directive tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. www.tenouk.com, ©

The syntax is one of the following, #include "path-spec" #include <path-spec> Both syntax forms cause replacement of that directive by the entire contents of the specified include file. The difference between the two forms is the order in which the preprocessor searches for header files when the path is incompletely specified. Preprocessor searches for header files when the path is incompletely specified. www.tenouk.com, ©

STRUCT, TYPEDEF, ENUM & UNION Step: Firstly, add new header file to the existing project. www.tenouk.com, ©

STRUCT, TYPEDEF, ENUM & UNION Step: Put the meaningful header file name. www.tenouk.com, ©

Abstract Data Types A programmer-created data type that specifies legal values that can be stored operations that can be done on the values The user of an abstract data type does not need to know any implementation details (e.g., how the data is stored or how the operations on it are carried out)

Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented programming is based on the data and the functions that operate on it. Objects are instances of Abstract Data Types, or ADTs.

Limitations of Procedural Programming Use of global data may allow data corruption Programs are often based on complex function hierarchies difficult to understand and maintain difficult to modify and extend easy to break