CS 220 Data Structures - PowerPoint PPT Presentation

1 / 55
About This Presentation
Title:

CS 220 Data Structures

Description:

incrDate(); Change the date it previously held to the next day. Precond: None. ... Returns true if the year is a leap year and false otherwise. Precond: None. ... – PowerPoint PPT presentation

Number of Views:59
Avg rating:3.0/5.0
Slides: 56
Provided by: ruthu
Category:
Tags: data | structures

less

Transcript and Presenter's Notes

Title: CS 220 Data Structures


1
CS 220 Data Structures
  • Instructor
  • Prof. Carolyn Pe Rosiene

2
Course Prerequisites
  • CS 115, minimum grade of C
  • Ability to write programs in C that involve
    loops, selection, arrays, and functions.
  • Ability to write object-oriented programs in C.
  • Ability to test and debug programs.
  • Basic problem solving skills.

3
This course is required for
  • CS 320 Programming Languages
  • CS 351 Intro to Artificial Intelligence
  • CS 360 Software Development
  • CS 362 - UNIX Internals
  • CS 371 - Computer Graphics
  • CS 375 - Internet Programming Concepts
  • CS 451 - Operating Systems
  • Some CS 330/331 Special Topics
  • - Required (Core) Courses in the Major

4
Words of Wisdom
  • This is a very demanding course.
  • Dont allow yourself to get behind.
  • Read the text before coming to class.
  • I expect you to ask questions.
  • Learning requires participation and involvement
    with the course material.

5
Data Structures with CUsing STL
  • Chapter One
  • Introduction to
  • Data Structures

6
Some terminology
  • A data structure is a systematic way of
    organizing and accessing data.
  • An abstract model of a data structure that
    specifies the data and the operations which are
    valid on the data, is called an abstract data
    type or ADT.
  • ADTs are implementation-independent. They express
    what is done, not how it is done.
  • We choose a specific implementation of ADTs to
    use in our programs.

7
ADT Operation Description
  • operationName
  • Preconditions
  • Postconditions
  • Action statement that specifies the input
    arguments, the type of operation on the elements
    of the data structure and the output value.
  • Necessary conditions that must apply to the input
    arguments and the current state of the object to
    allow successful execution of the operation
  • Changes in the data of the structure caused by
    the operation

8
An Example - Date ADT
  • readDate() Input from the keyboard the month
    day and year for a Date object, using the
    format mm/dd/yy.
  • Precond None.
  • Postcond Date object set to the date input.
  • writeShortDate() Outputs the date in the format
    mm/dd/yy.
  • Precond None.
  • Postcond None.
  • incrDate() Change the date it previously held
    to the next day.
  • Precond None.
  • Postcond Object is the day after the original
    value.

9
An Example - Date ADT continued
  • duration(d) Returns the number of days between
    the objects date and the date d.
  • Precond d must be later than the object date.
  • Postcond None.
  • getDay() Returns the day of the month for the
    date object.
  • Precond None.
  • Postcond None.
  • getYear() Returns the year for the date object.
  • Precond None.
  • Postcond None.

10
An Example - Date ADT continued
  • get Month() Returns the month of the date
    object.
  • Precond None.
  • Postcond None.
  • numberOfDays()Returns the day of the year for
    the date object.
  • Precond None.
  • Postcond None.
  • setDay(d) Changes the day part of the object
    to the specified day.
  • Precond d must be less than or equal to 31
  • Postcond The day part of the object has the
    value d.

11
An Example - Date ADT continued
  • setMonth(m) Changes the month part of the
    object to the specified month.
  • Precond m must be less than or equal to 12 and
    greater than 0
  • Postcond The month part of the object has the
    value m.
  • setYear(y) Changes the year part of the object
    to the specified year.
  • Precond y must be between 1000 and 9999
    inclusive.
  • Postcond The year part of the object has the
    value y.
  • isLeapYear() Returns true if the year is a
    leap year and false otherwise.
  • Precond None.
  • Postcond None.

12
Implementing ADTs in C
  • The class declaration in C allows us to define
    the data and operation interface.
  • A class implementation in C allows us to
    implement the operations, specific to the data
    definition.
  • An object is a specific instance of a class,
    which is used in the program.
  • A client is a program which uses objects.

13
The C Class Type
  • A class is a user defined type with data items
    and functions (methods).The data items and
    methods are referred to as class members.
  • The members and methods have access levels
    associated with them.
  • private - only the class members have access
  • public - client programs and class members have
    access.
  • protected - use with inheritance (to be discussed
    later)

14
Public and Private
  • The public section defines the information,
    generally the methods, that may be used by the
    client directly.
  • The private section defines the information which
    is hidden from the client, generally the data
    members and functions used to support the methods
    but not needed by the client.

15
Diagram of access levels
private Data Methods
class members
public Data Methods
External client programs
Good practice Declare data private to protect
it. Supply method to access and modify the
data as needed.
16
Diagram of Class Date
  • Date Class
  • private day
  • month
  • year
  • public constructor getDay
  • readDate getYear
  • writeShortDate getMonth
  • writeLongDate numberOfDays
  • incrementDate setDay
  • duration setYear
  • isLeapYear setMonth

17
Encapsulation and Information Hiding
  • The class encapsulates information by bundling
    the data and the methods, treating them as a
    single entity.
  • The class provides information hiding because the
    data members and the information about their
    implementation is not available to the client.
    Also the implementation of the methods is hidden
    from the client.

18
Polymorphism
  • Allows for more than one function or method with
    the same name but different parameters and
    implementation.
  • Functions or methods must differ in one of the
    following ways.
  • number of parameters
  • type of parameters
  • class that it is a member of
  • The type for the return value may not be the only
    difference.

19
Types of Methods
  • Constructors - creates a new instance of a class
    and initializes it.
  • Transformers - change the state of one or more
    private data members.
  • Observers - report the state of a private data
    member.
  • Summary - perform a computation on the objects
    private data but do not change it.
  • Iterators - allow you to move through a
    collection of objects.
  • Destructors - destroy an instance of the object
    when it goes out of scope.

20
Constructors
  • Purpose - initializes object when it is created.
  • Defining -
  • Has the same name as the class.
  • Never has a return type, not even void.
  • Parameters are optional
  • Default constructor- constructor with no
    parameters, or all parameters have default values
  • A class may have more than one constructor.

21
Definition of a class
  • Class definition
  • specifies the name of the class,
  • the private data and private methods if any,
  • the public data and methods.
  • Data is specified with a declaration statement.
  • Methods are specified as function prototypes.
  • The class definition is normally placed in a file
    named className.H

22
Use of const
  • Use the modifier const after any method which
    does not change the state of the object.
  • Example
  • void writeShortDate( ) const

23
Default arguments
  • A default value may be given to a parameter in
    case an argument is not supplied for that
    parameter.
  • There are four rules that must be followed
  • The default is only specified in the function
    prototype.
  • If any parameter is given a default all
    parameters to the right must also have default
    values.
  • If any argument is omitted, all arguments to the
    right of it must be omitted.
  • Default arguments may be expressions, provided
    the expression is valid at that point.

24
Enumerated Data
  • Programmer defined data type with a fixed set of
    constants.
  • Each constant is mapped to an integer
  • Operations allowed
  • Assignment
  • Relational operations

25
Enumerated Data Example
  • enum color_t WHITE, BLUE, GREEN, YELLOW,
    ORANGE, RED, VIOLET, BLACK
  • This definition creates a new type color_t. The
    identifiers, such as BLUE and RED, are constants
    and assigned value in sequence starting with 0.
  • color_t Color1, Color2
  • Color1 BLACK
  • Color2 RED
  • Color1 lt Color2 //7lt5 false

26
C Definition of Class Date
  • class Date
  • private
  • // private type used by date
  • enum monthName Jan 1, Feb, Mar, Apr,
    May, Jun, Jul, Aug,Sep, Oct, Nov, Dec
  • int day, month, year
  • public
  • Date(void) // Default constructor
  • Date(int d, int m, int y) // Constructor
  • void readDate()
  • void writeShortDate() const
  • void writeLongDate() const

27
C Definition of Class Date cont.
  • void incrementDate(int days)
  • int duration(Date d)const
  • int getDay()const
  • int getYear()const
  • int getMonth()const
  • int numberOfDays()const
  • void setDay(int d)
  • void setMonth(int m)
  • void setYear(int y)
  • bool isLeapYear()const

28
Implementing the Class
  • In the implementation, we implement each method.
  • Methods may be implemented in a separate file or
    inline, in the class definition.
  • Methods are implemented similar to functions.
  • Each method has an implied self, the object used
    to invoke the method.

29
Implementing Methods
  • To emphasize the separation of class definition
    from class implementation and the principle of
    information hiding, we will generally implement
    the methods in a separate file named
    className.cpp
  • When methods are implemented in a separate file
    the scope resolution operator, must be used to
    associate the method with its class.

30
Efficiency and in-line code
  • Implementing a method with in-line code means
    supplying the implementation in the function
    definition.
  • A method may be implemented using in-line code,
    if it is small.
  • Do not include the name of the class with scope
    resolution operator when implementing with
    in-line code.
  • In-line code replace the function call in the
    program, replacing the formal arguments with the
    actual arguments.
  • It makes the code longer but for very short
    functions, may also improve the run-time
    efficiency of the program.

31
Referencing Objects in a Method
  • Reference the private data of self using just the
    data member names, and invoke other methods using
    self, as if they are functions.
  • Arguments which are objects of that class being
    implemented, can reference their private data
    members using the objectName.memberName. The
    invoke methods of the class using message passing
  • If the objects are of a different class, they
    must use message passing to access the private
    data members.

32
Message Passing
  • The client accesses the public members and
    methods through a process called message passing.
  • The client passes a message to a receiving
    object, the object then performs the desired
    operation.
  • The C syntax for message passing is
    object.function_name(parameter_list)

33
Objects and Information Passing
  • Objects
  • may be passed to a function or method as either a
    value or reference parameter.
  • may be the value returned by a function or
    method.
  • Recall that when a parameter uses call by
    reference, the data type and the parameter name
    are separated by an ampersand, .

34
Implementation of Class Date
  • DateDate(void) // Default Constructor
  • day 1
  • month 1
  • year 1950
  • DateDate(int d, int m, int y) // Constructor
  • day d
  • month m
  • year y

35
Implementation of Class Date
  • void DatereadDate(void)
  • char slash
  • cout ltlt Enter a date month/day/year
  • cin gtgt month gtgt slash gtgt day gtgt slash gtgt year
  • void DatewriteShortDate(void)const
  • cout ltlt month ltlt / ltlt day ltlt / ltlt year

36
  • void DatewriteLongDate()const
  • switch (monthName(month))
  • case Jan cout ltlt January break
  • case Feb cout ltlt February break
  • case Mar cout ltlt March break
  • case Apr cout ltlt April break
  • case May cout ltlt May break
  • case Jun cout ltlt June break
  • case Jul cout ltlt July break
  • case Aug cout ltlt August break
  • case Sep cout ltlt September break
  • case Oct cout ltlt October break
  • case Nov cout ltlt November break
  • case Dec cout ltlt December
  • cout ltlt day ltlt , ltlt year

37
  • int Dateduration(Date c)const
  • int CDoY, // day of year for c DDoY, //
    day of year for self
  • DaysInYear, // number of days in that year
  • timeBetween0, // time between d and self
  • I // loop index
  • // determine the day of year for self and
    argument c
  • CDoY c.getDayOfYear()
  • DDoY getDayOfYear()
  • // determine number of days (c - self)
  • if (c.year year)
  • if (CDoY gt DDoY) timeBetween CDoY-DDoY
  • else
  • cout ltlt "\nError Precond. of duration not
    met.\n"
  • timeBetween -1

38
  • else if (c.year gt year)
  • for (Iyear Iltc.year I)
  • if (LeapYear(I)) DaysInYear 366
  • else DaysInYear 365
  • if (Iyear) timeBetween DaysInYear
    - DDoY
  • else timeBetween DaysInYear
  • timeBetween timeBetween CDoY
  • else
  • cout ltlt "\nError Precond. of duration method
    not met.\n"
  • timeBetween -1
  • return timeBetween
  • . . .

39
include
  • The include command copied the entire file in at
    the spot it appears.
  • Use this command in the .cpp file which
    implements the class and in the client program
    which uses the class.
  • The definition file may also use this command if
    it needs other .h files, either to define private
    data or to define parameters or return values.

40
What files get included
  • If the .h file defines a parameter or return type
    from another class the .h file for that class
    must be included.
  • For example deck.h must include card.h
  • The .cpp file will include the .h file for the
    class being implemented. This automatically
    includes all files included by the .h file.
    Therefore you only need to include files which
    contain methods, operators, functions, types or
    constants which were not previously included.
  • For example deck.cpp must include deck.h but
    does not need to include card.h
  • Remember, entities must be defined prior to being
    used.

41
Preprocessor commands and classes
  • Class definitions are normally enclosed with a
    sequence of preprocessor commands which prevent
    the including of the definition more than once in
    a client.
  • ifndef classname_h
  • define classname_h
  • the class defintion
  • endif

42
Defining Objects
  • Objects are declared the same way variables are
    declared, the class name is the data type in the
    declaration.
  • Syntax
  • className objectName
  • or
  • className objectName(argumentList)
  • Example
  • Date someday // uses default constructor
  • Date NewYearsDay(1,1,2002) // uses
    parameterized // constructor

43
An Example using Date class
  • Write a program that will help the librarian
    calculate the fine amount for a library book,
    given that the fine is 0.15 per day the book is
    late. The program will first input the current
    date, then it will process a sequence of late
    books, where for each late book the librarian
    will enter the due date. The program will print
    the number of days the book is late and the fine.

44
Implementation of Date Example
  • include ltiostream.hgt
  • include ltiomanip.hgt
  • include "date.h"
  • int main()
  • const double fineRate 0.15
  • Date currentDay
  • Date dueDate
  • int daysOverdue
  • double fine
  • char answer

45
cout ltlt "Enter the current date when
prompted\n" currentDay.readDate() do
cout ltlt "Enter the due date of the
book\n" dueDate.readDate() daysOverdue
dueDate.duration(currentDay) fine fineRate
daysOverdue cout ltlt "The book is " ltlt
daysOverdue ltlt " days
overdue.\n" cout ltlt "The fine is " ltlt
setiosflags(iosfixediosshowpoint)
ltlt setprecision(2) ltltfine ltlt endl cout ltlt "Do
you want to enter another book? (Y/N)\n" cin gtgt
answer while ((answer 'Y') (answer
'y')) cout ltlt "End of day\n"
return 0
46
Testing Classes
  • Each class should be tested by developing a short
    client program which invokes each public method
    to determine if it is working correctly.

47
Control Module Testing
  • Structured walk-through - showing the design and
    implementation to another programmer and explain
    exactly what is happening.
  • Clarifies the logic
  • Locates conceptual errors, and possibly other
    errors
  • Suggests test cases
  • Using source-level debugger to simulate execution
    of program and display values of objects, and
    variables, run-time stack, etc.
  • Uncover logic errors during execution of program

48
Test Data
  • A program can never be proved to be bug free by
    testing!
  • Test data should include
  • simple data
  • typical data
  • extreme data that test special cases and limits
  • invalid data
  • Every algorithm in the program should be tested.

49
Robustness
  • Robustness is a measure of the program's ability
    to identify invalid data, return error messages,
    and keep running if appropriate.

50
Application Programming Interface (API)
  • The API provides all of the information which the
    user of a class, the client, needs to use the
    class.
  • The API includes the className, the header files
    where the class is defined, the function
    prototypes for the constructor and the operations
    of the class and the preconditions and
    postconditions for using those operations.
  • It will be used throughout the course to describe
    classes.

51
API for random number class
CLASS randomNumber Constructors
d_random.h
randomNumber(int seed 0) Sets the seed for
the random number generator Postconditions
With the default value 0, the system clock
initializes the seed otherwise the user
provides the seed for the generator.
CLASS randomNumber Operations
d_random.h
double frandom () Return a real number x,
0.0 lt x lt1.0 int random() Return a 32-bit
random integer m, 0 lt m lt 231-1 int random(int
n) Return a random integer m, 0 lt m lt n
52
C-style Strings
  • In C, strings are represented as character arrays
    which are terminated by the NULL character,\0.
  • Only when a character array contains the NULL
    character is it a character string.
  • include ltcstring.hgt to access the functions
    available for manipulating C-style strings.
  • string literals are represented as C-style
    strings.
  • the file name used to open a file must be a
    C-style string.

53
The String Class
  • The standard template library provide a class for
    the string ADT.
  • Include ltstring.hgt to use the string class.
  • A string object contains a sequence of characters
    and the length of the string.
  • Many methods are provided to help manipulate
    string objects.

54
Advantages of the string class
  • It provides input for lines as well as words.
  • gtgt can be used to input words, since it stops
    at the first whitespace character.
  • getline function will input and entire line.
  • The assignment operator can be used to copy
    strings.
  • The relational operators can be used to compare
    strings.

55
More Advantages of string class
  • Strings can be joined using the , and
    operators.
  • Individual characters of a string can be accessed
    as if it were an array.
  • There are a wide variety of string methods for
    manipulating strings. (See text for details on
    some of them).
Write a Comment
User Comments (0)
About PowerShow.com