Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.

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.
C Language.
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.
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.
Structure.
Data Structures Lecture 3: Struct Azhar Maqsood NUST Institute of Information Technology (NIIT)
ISBN Chapter 6 Data Types: Structured types.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
Chapter 9: Arrays and Strings
 2003 Prentice Hall, Inc. All rights reserved Introduction Object-oriented programming (OOP) –Encapsulates data (attributes) and functions (behavior)
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
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.
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.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Programming Initializing Data of Struct Type. COMP102 Prog. Fundamentals: initialize struct type/ Slide 2 Ex. 10: Initialize Data of struct Type l By.
Arrays One-Dimensional initialize & display Arrays as Arguments Part I.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Structured Data Types array array union union struct struct class class.
CS1201: Programming Language 2 Structure By: Nouf Almunyif.
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
Programmer Defined Structures (Records)
CPSC 252 Concrete Data Types Page 1 Overview of Concrete Data Types There are two kinds of data types: Simple (or atomic) – represents a single data item.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
Data Structures (Terminology) Static Set at compile time Dynamic Set at run time.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
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.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Structured Data Chapter 11. Combining Data Into Structures Structure: C++ construct that allows multiple variables to be grouped together Format: struct.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
Structures (aka records, structs) Textbook Chapter 11 sections:
Structures - Part II aggregate operations arrays of type struct nested structures compared to classes.
1 Structured Data (Lecture 11) By: Dr. Norazah Yusof FSKSM, UTM.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
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.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Class Method Read class Student { private: string id; string firstName, lastName; float gpa; public: // Will the method change any data members? // Yes!
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.
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.
Structure A collection of values (members) struct date{ int day; char month[10]; int year; }; Declare a structure variable struct date today; struct struct_name.
CGS 3460 Thus Far n Whenever we declare a variable, we specified its data type. n The data type helped us identify the type of information that a variable.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
114 3/30/98 CSE 143 Collection ADTs [Chapter 4] /30/98 Collection ADTs  Many standard ADTs are for collections  Data structures that manage groups.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
Topic 4 Data Structures Program Development and Design Using C++, Third Edition.
Structures and Classes
CO1401 Program Design and Implementation
Structures - Part II aggregate operations arrays of type struct
C++ Data Types Simple Structured Address Integral Floating
Heterogeneous aggregate datatypes
Arrays An array is a collection of variables that all have the same name and the same data type. Each member of the array is known as an element of the.
Structured Data Types array union struct class.
Lec17 Structs.
Structures Structured Data types Data abstraction structs ---
Arrays Prepared By Paritosh Srivastava PGT (CS) KV NHPC Banbasa.
Presentation transcript:

Structured Data Types struct class

Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type collections of different types

Structured Data Types struct is a user defined data type with a fixed number of components that are accessed by name, not by index. Each component is called a field or a member

Structure Declaration struct MyDateType { int month; int day; int year; }; for above, the struct members are month, day, and year struct TAG

Representation in Memory monthdayyear struct Employee { int id; char name[15] double salary; }; Employee Emp1 = {1234, “Smith”, 5.6}; id name salary S m i t h \0 5.6 each cell represents 1 byte, so an int is stored in 4 bytes, name has 15 bytes reserved and salary is a double 8 bytes members can be arrays! or other structs!

Structure declaration specifying a template like creating your own datatype Object declaration or variable declaration or object instantiation using your own data type

Object Declaration/Instantiation int num; double x; MyDateType myBirth, today, tomorrow; data type variable name

Declaration and Initialisation Date myBirth = {4, 2, 1980}; Date today = {11, 25, 1999}; Date tomorrow = {3, 25, 2001};

Assigning Values myBirth = {4, 2, 1980}; today = {11, 25, 1999}; tomorrow = {3, 25, 2001}; Illegal ! Legal ! myBirth = today;

Assigning Values myBirth.month = 4; myBirth.day = 2; myBirth.year = 1980; today.month = 3; today.day = 25; today.year = 1995; instance of DateType member of myBirth instance Note dot, This is the member selection operator

Accessing struct Values // to assign to a basic variable year = today.year new_mo = today.month + 1 // to assign contents of a variable to a structure member today.month = someMonth;

keyboard input Date today, bill_date; cout << “Enter month, day and year: “; cin >> today.month >>today.day >> today.year; bill_date = today;// an aggregate action cout << bill_date.month <<“ “ << bill_date.day; it should be easy to see how you can read from a file

Structures used as function arguments int Overdue( Date now, int purchaseyear); Overdue(today, bill_Date.year); int Overdue(Date &now, int purchaseyear); Overdue(today, bill_Date.year); Pass by value Pass by reference

Pass by value and Pass by reference The same rules apply to structure objects as to basic atomic data. You can pass a structure by value, the argument passes a copy of individual members to the receiving parameter. in previous slide the argument today was copied to parameter now. You can specify the function to pass by reference by use of the reference symbol &.

Aggregate Operations OperationArrays Structs I/ONo ( except strings )No AssignmentNo Yes ArithmeticNo No ComparisonNo No Parameter pass.Ref. only Either value or ref. Funct. return value No Yes

Arrays of Structures struct PrisonerRecord{ char lastName[20]; char firstName[20]; char Occupation[20]; char MaritalStatus[20]; int age; char BirthPlace[20]; }; // array of 100 elements, each of type PrisonerRecord PrisonerRecord Prisoner[100];

Arrays of Structures //Load data into array i =0; while (fin >>Prisoner[i].lastName >> Prisoner[i].firstName >> Prisoner[i].Occupation >> Prisoner[i].MaritalStatus >> Prisoner[i].age >> Prisoner[i].BirthPlace) { i++; } DEMO1 CHRIS

Another example of Arrays of Structures struct Payroll { int id; char name[15]; double payrate; }; // an array of 3 records of type Payroll Payroll employee[3]; Consider the structure below

Arrays of Structures // load array -- there are other ways to load the array Payroll employee[3] = { {11, “Bill”, 7.25}, {12, “Paul”, 6.50}, {13, “Maria”, 9.00} }; // display array for(i = 0; i < 3; i++) { cout << ‘\n’ << employee[i].id << setw(20) << employee[i].name << setw(20) << employee[i].payrate; }

Arrays of Structures and functions // prototypes struct Payroll { int id; char name[15]; double payrate; }; void loadarray(Payroll staff[ ], int nItems); void showarray(Payroll staff[ ], int nItems); int main(){ //declare array of 3 records of type Payroll and initialize the first record Payroll employee[3]; loadarray(employee,3);// calls showarray(employee,3); cout << endl; return 0; }

Arrays of Structures // load array - data typically entered via file input void loadarray(Payroll staff[ ], int nItems) { int i; for(i = 0; i < nItems; i++) { cout << "Enter the ID, name, and pay rate: "; cin >> staff[i].id >> staff[i].name >> staff[i].payrate; cout << endl; } }

Arrays of Structures void showarray(Payroll staff[ ], nItems){ int i; cout << setiosflags(ios::fixed) << setprecision(2); for(i = 0; i < 3; i++) { cout << '\n' << setw(5) << staff[i].id << setw(13) << staff[i].name << setw(10) << staff[i].payrate; } }

Nested Structures struct ListData { int id; char name[15]; double payrate; }; struct List { int MaxSize; int nItems ListData Record[100] }; Called a Meta Structure

Nested Structures // declaration of an List object //List contains an array of ListData structures List MyEmployees; // Initialise list data MyEmployees.MaxSize = 100; MyEmployees.nItems = 0; //Add a record MyEmployees.Record[0].ID = 123; strcpy(MyEmployees.Record[0].Name, “SMITH”); MyEmployees.Record[0].payrate = 10.50; MyEmployees.nItems++; Note syntax use of dots to refer to members. if a member is a struct, then refer to its members using dot notation

Abstract data types ADT’s Example : A list ADT A list has max length number of objects currently stored objects Operations create list (initialise list members) add object display list remove object destroy list search list for an object sort list check if list is full check if list is empty etc.

Definition of ADT Most languages have concrete data types- C++ has int, char, float, etc. The data type determines the range of legitimate values and the operations that can be performed. The data types provided by the language are called concrete data types. During the design of a program the need for new data types may arise. for example a record in a database or indeed a whole data base. These objects have ranges of legitimate values and records and databases have legitimate operations. A formal specification of such objects, defining legitimate ranges and valid operations is an abstract data type. See previous slide. NOTE it must not be specified in C++ form.

Implementation of ADT’s using structs declare a struct for the data declare a struct for the ADT, one member will be the data struct, other typical member is the number of items stored. Initialise/create an ADT object sets the initial members Create functions that operate on the ADT object.

A List ADT Implementation const int MAXSIZE = 100; //declare a struct for the data struct ListData { int id; char name[15]; double payrate; }; //declare a struct for the abstract data type struct List { int MaxSize; int nItems; ListData Record[MAXSIZE] }; //operation prototypes void CreateList(List & list); void AddToList(List & list, ListData newdata); void DisplayList(List & list);

A List ADT Implementation int main(void) { //declare two lists List A; ListData temp; // a temporary variable to add records CreateList(A);//constructs lists by setting up size to MAXSIZE // and nItems to zero cout << Enter employee ID, followed by Name and then rate of pay : “; cin >> temp.ID >> temp.name >> temp.payrate; AddToList(A,temp); DisplayList(A); return 0; }

operation definitions //operation definitions for list “construction” void CreateList(List & list){ list.MaxSize = MAXSIZE; list.nItems = 0; }

operation definitions //Notice how array subscript is a member of struct i.e list.nItems is used to refer //to next free element in array. void AddToList(List & list, ListData newdata) { list.Record[list.nItems].id = newdata.id; list.Record[list.nItems].payrate = newdata.payrate; strcpy(list.Record[list.nItems].name,newdata.name); //now increment nItems member list.nItems++; }

operation definitions void DisplayList(List & list){ int i; cout << "There are " << list.nItems << " Employees in the list" << endl; for (i=0;i<list.nItems; i++) { cout << list.Record[i].id <<" "<< list.Record[i].name <<" "<< list.Record[i].payrate << endl; } DEMO2

Things to come - binding data to functions that use the data. Functions are loosely associated with structure. It would be nice if the data and operations were bound together. We can! but C++ only, not C Add function prototypes to struct declaration. Even more tight connection between data and operations via classes.