Structured Data Dr. Jose Annunziato. Abstract Data Types Abstract Data Types (ADTs) are custom types that are defined in terms of other types, including.

Slides:



Advertisements
Similar presentations
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Advertisements

Structure.
More methods and classes, 4 of 4 Math 130 Introduction to Programming Lecture # 18 Monday, October 8, 2007.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Constants. 2 Objectives Describe ways to create constants –const –readonly –enum.
Function tax and buy_one double tax (double price, double tr) { return price*tr; } double buy_one() { double p; cout > p;
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
1 Abstract Data Type (ADT) a data type whose properties (domain and operations) are specified (what) independently of any particular implementation (how)
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.
More Storage Structures A Data Type Defined by You Characteristics of a variable of a specific ‘data type’ has specific values or range of values that.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
Object-Oriented Programming in C++
CSC 107 – Programming For Science. Today’s Goal Variables  Variable  Variable name location to store data  Only for humans; 0 x 7E8A2410 harder to.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
CSCI-383 Object-Oriented Programming & Design Lecture 5.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
1 Object-Oriented Programming Using C++ CLASS 5. 2 Object Composition Object composition occurs when a class contains an instance of another class. Creates.
Introduction to Computer Science 2 Slide 1 Enumerated types We already know some data types int, float, char good for problems that involve int,
CSCI 383 Object-Oriented Programming & Design Lecture 6 Martin van Bommel.
Chapter 9 Structured Data: Structs and ADTs (Data Base Programs with C++) Mr. Dave Clausen La Cañada High School.
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
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 © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
C++ Classes and Data Structures Jeffrey S. Childs
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Programming Fundamentals. Today’s Lecture The Conditional Operator Logical Operators Structures Enumerations.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Structured Data and Classes
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CSci 162 Lecture 2 Martin van Bommel. Enumeration –process of listing all of the elements in the domain of a type Enumerated type –type defined via enumeration.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
STRUCTURED PROGRAMMING Selection Statements. Content 2  Control structures  Types of selection statements  if single-selection statement  if..else.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
Pointers A pointer type variable holds the address of a data object or a function. A pointer can refer to an object of any one data type; it cannot refer.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
1 1  Lecture 11 – Structured Data FTMK, UTeM – Sem /2014.
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.
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
2-Oct-16 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Chapter 12 Classes and Abstraction
11 Chapter Structured Data
Selection (also known as Branching) Jumail Bin Taliba by
Pointers, Enum, and Structures
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
Object-Oriented Programming: Classes and Objects
Built-In (a.k.a. Native) Types in C++
Chapter 11: Structured Data.
Standard Version of Starting Out with C++, 4th Edition
Chap 2. Identifiers, Keywords, and Types
More on Structs Sometimes we use structs even when the fields are all of the same type. If the fields are different conceptually, that is, the data stands.
Linked Lists Dr. Jose Annunziato.
Presentation transcript:

Structured Data Dr. Jose Annunziato

Abstract Data Types Abstract Data Types (ADTs) are custom types that are defined in terms of other types, including primitive types and other ADTs ADTs define the data being operated on as well as the family of operations that manipulate the data C++ provides two mechanisms to define ADTs – Structures – Classes

Structures Use the struct keyword to define a new data type struct Employee { string firstName; string lastName; int age; float salary; string hireDate; }

Transaction ADT We group the variables for our bank application into a structure struct Transaction { string date; int type; string description; float amount; } Notice struct does not contain balance

Declaring Variables of New Type Declaring variables consists of declaring the type of the variable, and then the name of the variable For structures it is no different. Declare a new variable with the new data type as its type The size of memory needed to hold the new variable is the sum of the individual members of the structure Employee alice, bob, charlie; Transaction deposit1, deposit2, withdraw1;

Struct Vs. Parallel Arrays Structures are an improvement over the parallel array representation Instead of having several arrays representing various records, a single record can be represented by a single structure instance date[]type[]description[]amount[]balance[] 7/11/12DEPOSITOpen Account /12/12WITHDRAWGroceries /13/12DEPOSITWages /14/12WITHDRAWPharmacy withdraw1

Accessing Structure Members Once a variable has been declared to be of a type, the individual members can be accessed using the dot notation This consist of using the "." in between the name of the variable and the name of the property Parent / Child relation or "Has A" relation alice.firstName = "Alice"; alice.salary += ; deposit1.amount = 200.0; cout << bob.hireDate << endl;

Comparing Structures To compare structures, compare each of the elements Transaction t1, t2; bool transactionsEqual = false; if ( t1 == t2 ) transactionsEqual = true;// X if ( t1.date == t2.date &&// OK t1.type == t2.type && t1.description == t2.description && t1.amount == t2.amount && t1.balance == t2.balance ) transactionsEqual = true;

Initializing a Structure Structures can be initialized when they are declared by providing all or some of the values for their members Employee charlie = { "Charlie", "Steel", 42, 75000, "9/1/2012" }; Transaction deposit2 = { "7/15/ :22:33", 0, "wages", }; Transaction withdraw1 = { "…", 1, "…" }; You can't skip initializations Employee bob = { "Robert",, 62,, };

Arrays of Structures Use arrays to handle various instances of structures of the same type Arrays of structures are declared using the same syntax as for primitive data types EmployeehourlyEmployee[10]; EmployeesalariedEmployee[100]; TransactionmonthlyStatement[31]; Transaction yearEndStatement[365]; Wouldn’t it be great to relate hourlyEmployees and salariedEmployees? Classes will allow this…later

Nested Structures Structures can group any other data types including other ADTs For instance, instead of using string data type for dates, we can declare a data type that better represents the data structure Date { int month, day, year; int hour, minutes, seconds; } ADTs allow thinking about problems at proper abstraction

Declare Data Types as Members structure Employee { string hireDate; Date hireDate; … } structure Transaction { string date; Date date; … }

Define Data Type Instance as Member Define a data type instance and assign as a member Date hireDate = { 7, 11, 2012, 4, 55, 34 }; Employee charlie = { …, hireDate, … }; Date depositDate = { 6, 10, 2012, 3, 4, 5 }; Transaction openAccount = { depositDate, … }; You can change the structure after definition depositDate.day = 11; Transaction deposit2; deposit2.date = depositDate;

Traversing Nested Types Similar to using / or \ to navigate a directory path, use the dot (.) notation to navigate nested types struct Employee { Date lastRaise; float salary; } Employee charlie; charlie.salary += ; charlie.lastRaise.month = 7; charlie.lastRaise.day = 14; charlie.lastRaise.year = 2012;

Traversing Nested Data Type Arrays struct Account { Transaction transactions[]; int transactionCount; } Account checking; for ( int s = 0; s < checking.transactionCount; s++ ) { cout << checking.transactions[ s ].balance; }

Use Ctime To Get Current Time The ctime library already declares a time structure #include … time_t rawTime = time ( 0 ); struct tm * timeInfo = localtime ( &rawTime ); Date hireDate = { timeInfo->tm_mon, timeInfo->tm_mday, timeInfo->tm_year };

Passing Structures to Functions Like regular variables, structure variables can be passed to functions by value or by reference Passing by value copies the variable onto the parameter and the function can not change the original variable Passing by reference does copy the variable and allows the function to act on the original variable Use the & operator to pass by reference just like regular variables

Giving Everyone a Raise void giveRaise (Employee &employee, float percent ); int main() { Employee alice; giveRaise ( alice, 7 ); Employee employees [ 2300 ]; for ( int e = 0; e < 2300; e++ ) giveRaise ( employee [ e ], 5 ); } void giveRaise (Employee &employee, float percent ) { employee.salary *= ( percent / ) + 1; }

Constant Structures Even though a function does not change the parameter structure, you might want to pass it as reference anyway if the structure is too large Declare parameters as const if they should not be changed by function void printEmployee ( const Employee &employee ) { cout << employee.firstName << " "; cout << employee.lastName << endl; … }

Returning Structures from Functions Functions can create structure instances; these are sometimes called factories Employee* employeeFactory ( string fName, string lName, float salary, Date hireDate ) { Employee* employee = new Employee; employee->firstName = fName; employee->lastName = lName; employee->hireDate = hireDate; employee->salary = salary; return employee; }

Get Current Date #include Date getCurrentDate() { time_t rawTime = time ( 0 ); struct tm * timeInfo = localtime ( &rawTime ); Date dateNow = { timeInfo->tm_mon,timeInfo->tm_mday, timeInfo->tm_year,timeInfo->tm_hour, timeInfo->tm_min,timeInfo->tm_sec }; return dateNow; }

Transaction Factory Factories hide details for creating instances Transaction createTransaction ( int type, float amount, string description ) { Transaction tx; tx.date = getCurrentDate(); tx.type = type; tx.description = description; tx.amount = amount; return tx; }

Enumerated Data Types Enumerated data types define enumerators, named values that represent sequential integer values Enumerations are a better alternative to constant integers and improve type checking Useful for defining a group of related integer values Use enum keyword to define enumerations enum TransactionType { DEPOSIT, WITHDRAW, TRANSFER }; TransactionType type1 = DEPOSIT;

Enumerators Must Be Unique Enumerators belong to the same name space enum Presidents { MCKINLEY, ROOSEVELT, TAFT }; enum VPs { ROOSEVELT, FAIRBANKS, SHERMAN }; You can not re-declare the enumerator even if it has the same value; enum Status { ON, OFF }; int OFF = 1;

Enumerators are Integers By default enumerators are assigned values 0, 1, 2… You can print the enumerators and they will print their integer equivalent cout << DEPOSIT << endl; cout << WITHDRAW << endl; cout << TRANSFER << endl;

Overriding Enum Integer Values When you declare enum data types, you can specify the integer values of the enumerators enum Water { FREEZING = 0, BOLING = 100 }; You can not change the values of the enumerators after they are declared

Enumerating Transactions Instead of using constants or named integers, enums allow compilers to catch potential bugs struct Transaction { string date; int type; } enum TransactionType { DEPOSIT, WITHDRAW }; struct Transaction { Date date; TransactionType type; }

Enumerating Transactions Instead of using constants or named integers, enums allow compilers to catch potential bugs const int DEPOSIT = 0;// use enum instead const int WITHDRAW = 1; enum TransactionType { DEPOSIT, WITHDRAW }; … Transaction deposit = { …, DEPOSIT, … } Transaction withdraw; withdraw.type = WITHDRAW;

Can't Assigning Values to Enums You can not assign integer values to enumerators DEPOSIT = 45;// X It's a good thing since we don’t want to accidentally assign a bad integer to an enum type Transaction withdraw; withdraw.type = 0;// X We want to avoid mistakes such as Transaction withdraw; withdraw.type = 21;// X

Assigning Enumerators to int Variables Although you can not write to an enum, you can read it and use it as an integer enum Day = { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }; int x = THURSDAY; cout << x << endl; Day workDay = FRIDAY; int y = workDay; cout << y << endl;

Comparing Enumerator Values Since enums can be read as integers, they can be compared as such if ( FRIDAY > MONDAY ) cout << "Friday comes after Monday" << endl; if ( MONDAY == 0 ) cout << "Monday is the first day" << endl;

Iterating Over Enums You can use enumerators as array indices or as loop sentinels float dailyBalances[ 7 ]; dailyBalances [ MONDAY ] = 100.0; dailyBalances [ TUESDAY ] = 100.0; … dailyBalances [ SUNDAY ] = ; for ( int day = MONDAY; day < FRIDAY; day++ ) { cout << dailyBalances [ day ] << endl; }

Anonymous Enumerated Types If you don’t need to declare variables with the enum data type, there is no need to name the new type Use enum just to create the enumerators enum Day { MONDAY, TUESDAY, …, FRIDAY }; Here it is as an anonymous enumeration enum { MONDAY, TUESDAY, …, FRIDAY };

Changing Enums with Math Remember that you can not change the value of an enumerator If an enumerator is used in an arithmetic expression, the result is not an enumerator and therefore it can not be assigned to an enum Day day1, day2; day1 = TUESDAY; day2 = day1 + 1;// X

Using Enums in Switch Case A common use of enums is in switch statements to choose among various actions Day today; switch ( today ) { case MONDAY : case TUESDAY : … case FRIDAY : cout << "TGIF" << endl; break … }

Declaring Enums and Variables Together When declaring enumerations you can declare variables as well Instead of using 2 lines: enum TransactionType { DEPOSIT, WITHDRAW }; TransactionType type1; You can use 1 line: enum TransactionType { … } type1;

StructureDemo.cpp StructureDemoLibrary.h StructureDemoLibrary.cpp