1 / 80

Data Structures

Data Structures. Text: Data structures using C & C++ by Langsam, Augenstein, Tenenbaum Reference: C++ Plus Data Structures by Nell Dale Topics: Linked lists: Single & Doubly linked list applications Stacks: representation, operations, usage, and application

Télécharger la présentation

Data Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Structures Text: Data structures using C & C++ by Langsam, Augenstein, Tenenbaum Reference: C++ Plus Data Structures by Nell Dale Topics: Linked lists: Single & Doubly linked list applications Stacks: representation, operations, usage, and application Queues: representation, operations, usage, and application

  2. OtherTopics 4. Trees: types, representation, operations, usage, and application • Recursions: backtracking algorithms • Hashing: techniques, collisions and their resolution • Sorting methods: Heap sort • Priority queques.

  3. More information • Home work: there will be programming assignments. • Examinations: there will be two hourly exams and a final exam. • Grading: the total grade will be computed as follows: • 20% for each hourly exam • 10% for the home work • 50% for the final exam.

  4. Data Types & Data Structures • Data come in different forms and types. • Simple data types: such as integers (int), real numbers (float) and characters (char). • More complex built-in data types or structures such as arrays, records (struct) and files which are collections of data. • User defined data structures (the core of this course).

  5. Introduction • A computer algorithm is a detailed step-by-step method for solving a problem by using a computer. • Program = Algorithm + Data Structures

  6. What is this Course About? Clever ways to organize information in order to enable efficient computation • What do we mean by clever? • What do we mean by efficient?

  7. Clever? Efficient? Insert Delete Search Sort Traverse Manipulate Lists, Stacks, Queues Heaps Binary Search Trees Trees Hash Tables Graphs Disjoint Sets Data Structures Algorithms

  8. Programming Life Cycle Activities • Problem analysisunderstand the problem • Requirements definitionspecify what program will do • High- and low-level designhow it meets requirements • Implementation of designcode it • Testing and verificationdetect errors, show correct • Deliveryturn over to customer • Operation use the program • Maintenancechange the program

  9. Identifies various objects composed of data and operations, that can be used together to solve the problem. Divides theproblem intomore easily handled subtasks,until the functional modules (sub problems) can be coded. Two Approaches to Building Manageable Modules FUNCTIONALDECOMPOSITION OBJECT-ORIENTED DESIGN FOCUS ON: processes FOCUS ON: data objects

  10. Find Weighted Average Print Weighted Average Functional Design Modules Main Get Data Prepare File for Reading Print Data Print Heading

  11. Object-Oriented Design A technique for developing a program in which the solution is expressed in terms of objects -- self- contained entities composed of data and operations on that data. cin cout << >> setf get Private data Private data . . . . . . ignore

  12. More about OOD • Languages supporting OOD include: C++, Java, Smalltalk , and Eiffel. • Aclass is a programmer-defined data type and objects are variables of that type. • In C++, cin is an object of a data type (class) named istream, and cout is an object of a class ostream. Header files iostream.h and fstream.h contain definitions of stream classes.

  13. Procedural vs. Object-Oriented Code “Read the specification of the software you want to build. Underline the verbs if you are after procedural code, the nouns if you aim for an object-oriented program.” Grady Booch, “What is and Isn’t Object Oriented Design,” 1989.

  14. Program Verification • Program Verification is the process of determining the degree to which a software product fulfills its specifications. SPECIFICATIONS Inputs Outputs Processing Requirements Assumptions PROGRAM

  15. Verification vs. Validation Program verification asks, “Are we doing the job right?” Program validation asks, “Are we doing the right job?” B. W. Boehm, Software Engineering Economics, 1981.

  16. DATA SET 1 DATA SET 2 DATA SET 3 Program Testing • Testing is the process of executing a program with various data sets designed to discover errors. DATA SET 4 . . .

  17. cin (of type istream) cout (of type ostream) Keyboard and Screen I/O #include <iostream> output data input data executing program Keyboard Screen

  18. <iostream> is header file • for a library that defines 3 objects • an istream object named cin (keyboard) • an ostream object named cout (screen) • an ostream object named cerr (screen)

  19. Insertion Operator ( << ) • The insertion operator << takes 2 operands. • The left operand is a stream expression, such as cout. • The right operand is an expression describing what to insert into the output stream. It may be of simple type, or a string, or a manipulator (like endl).

  20. Extraction Operator ( >> ) • Variable cin is predefined to denote an input stream from the standard input device ( the keyboard ). • The extraction operator >> called “get from” takes 2 operands. The left operand is a stream expression, such as cin. The right operand is a variable of simple type. • Operator >> attempts to extract the next item from the input stream and store its value in the right operand variable.

  21. Extraction Operator >> • “skips”(reads but does not store anywhere) leading whitespace characters (blank, tab, line feed, form feed, carriage return) before extracting the input value from the stream (keyboard or file). • To avoid skipping, use function get to read the next character in the input stream. cin.get(inputChar);

  22. input data output data Disk files for I/O #include <fstream> disk file “A:\myInfile.dat” disk file “A:\myOut.dat” executing program your variable (of type ifstream) your variable (of type ofstream)

  23. For File I/O • use #include <fstream> • choose valid variable identifiers for your files and declare them • open the files and associate them with disk names • use your variable identifiers with >> and << • close the files

  24. Statements for using file I/O #include <fstream> ifstream myInfile; // declarations ofstream myOutfile; myInfile.open(“A:\\myIn.dat”); // open files myOutfile.open(“A:\\myOut.dat”); myInfile.close( ); // close files myOutfile.close( );

  25. What does opening a file do? • associates the C++ identifier for your file with the physical (disk) name for the file • if the input file does not exist on disk, open is not successful • if the output file does not exist on disk, a new file with that name is created • if the output file already exists, it is erased • places a file reading marker at the very beginning of the file, pointing to the first character in it

  26. File IO #include <fstream> // for file I/O int main( ) { // USES FILE I/O int partNumber; float unitPrice; ifstream inFile; // declare file variables ofstream outFile; inFile.open(“input.dat”); //open files outFile.open(“output.dat”); inFile >> partNumber ; inFile >> unitPrice ; outFile << “Part # “ << partNumber // echo << “at Unit Cost: $ “ << unitPrice << endl ; return 0; }

  27. Stream Failure • When a stream enters the fail state, further I/O operations using that stream are ignored. But the computer does not automatically halt the program or give any error message. • Possible reasons for entering fail state include: • invalid input data (often the wrong type), • opening an input file that doesn’t exist, • opening an output file on a diskette that is already full or is write-protected.

  28. IO Stream Failure #include <fstream> #include <iostream> int main( ) { // CHECKS FOR STREAM FAIL STATE ifstream inFile; inFile.open(“input.dat”); // try to open file if ( !inFile ) { cout << “File input.dat could not be opened.”; return 1; } . . . return 0; }

  29. A Walk-Through • Is a verification method using a team to perform a manual simulation of the program or design, using sample test inputs, and keeping track of the program’s data by hand. • Its purpose is to stimulate discussion about the programmer’s design or implementation .

  30. Data Abstraction • Separation of a data type’s logical properties from its implementation. LOGICAL PROPERTIES IMPLEMENTATION What are the possible values? How can this be done in C++? What operations will be needed? How can data types be used? 30

  31. APPLICATION REPRESENTATION 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 Data Encapsulation • is the separation of the representation of data from the applications that use the data at a logical level; a programming language feature that enforces information hiding. int y; y = 25; 31

  32. Encapsulated C++ Data Type int TYPE int Representation of int as 16 bits two’s complement + Implementation of Operations Value range: INT_MIN . . INT_MAX Operations: + prefix - prefix + infix - infix * infix / infix %infix Relational Operators infix (inside) 32

  33. Abstract Data Type (ADT) • A data type whose properties (domain and operations) are specified independently of any particular implementation. 33

  34. Data from 3 different levels • Application (or user) level: modeling real-life data in a specific context. • Logical (or ADT) level: abstract view of the domain and operations. WHAT • Implementation level: specific representation of the structure to hold the data items, and the coding for operations. HOW 34

  35. 4 Basic Kinds of ADT Operations • Constructor -- creates a new instance (object) of an ADT. • Transformer -- changes the state of one or more of the data values of an instance. • Observer -- allows us to observe the state of one or more of the data values without changing them. • Iterator -- allows us to process all the components in a data structure sequentially. 35

  36. Address pointer reference C++ Built-In Data Types Simple Composite Integral Floating array struct union class char short int long enum float double long double 36

  37. Two Forms of Composite Data Types UNSTRUCTURED STRUCTURED The organization determines method used to access individual data components. Components are not organized with respect to one another. EXAMPLES:EXAMPLES: arrays classes and structs 37

  38. thisCar at Base Address 6000 .year 1999 .maker ‘h’ ‘o’ ‘n’ ‘d’ ‘a’ ‘\0’ . . . .price 18678.92 Records A record is a composite data type made up of a finite collection of not necessarily homogeneous elements called members or fields. For example: 38

  39. struct CarType struct CarType { int year ; char maker[10]; float price ; } ; CarType thisCar; //CarType variables CarType myCar; 39

  40. Accessing struct members The member selection operator (period . ) is used between the variable name and the member identifier to access individual members of a record (struct or class) type variable. EXAMPLES myCar.year thisCar.maker[4] 40

  41. Valid struct operations • Operations valid on an entire struct type variable: assignment to another struct variable of same type, pass as a parameter to a function (either by value or by reference), return as the value of a function. 41

  42. CALLING BLOCK FUNCTION CALLED Pass-by-value sends a copy of the contents of the actual parameter SO, the actual parameter cannot be changed by the function. 42

  43. sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED Pass-by-reference can change value of actual parameter 43

  44. Using struct type Reference Parameter to change a member void AdjustForInflation(CarType& car, float perCent) // Increases price by the amount specified in perCent { car.price = car.price * perCent + car.price; } ; SAMPLE CALL AdjustForInflation(myCar, 0.03); 44

  45. Using struct type Value Parameter to examine a member bool LateModel(CarType car, int date) // Returns true if the car’s model year is later than or // equal to date; returns false otherwise. { return ( car.year >= date ) ; } ; SAMPLE CALL if ( LateModel(myCar, 1995) ) cout << myCar.price << endl ; 45

  46. One-Dimensional Array at the Logical Level A one-dimensional array is a structured composite data type made up of a finite, fixed size (known at compile time) collection of homogeneous (all of the same data type) elements having relative positions and to which there is direct access (any element can be accessed immediately). Array operations (creation, storing a value, retrieving a value) are performed using a declaration and indexes. 46

  47. Implementation Example This ACCESSING FUNCTION gives position of values[Index] Address(Index) = BaseAddress + Index * SizeOfElement float values[5]; // assume element size is 4 bytes Base Address 7000 7004 7008 7012 7016 values[0] values[1] values[2] values[3] values[4] Indexes 47

  48. One-Dimensional Arrays in C++ • The index must be of an integral type (char, short, int, long, or enum). • The index range is always 0 through the array size minus 1. • Arrays cannot be assigned, and cannot be the return type of a function. 48

  49. Another Example This ACCESSING FUNCTION gives position of name[Index] Address(Index) = BaseAddress + Index * SizeOfElement char name[10]; // assume element size is 1 byte Base Address 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 name[0] name[1] name[2] name[3] name[4] . . . . . name[9] 49

  50. Passing Arrays as Parameters • In C++, arrays are always passed by reference, and & is not used with the formal parameter type. • Whenever an array is passed as a parameter, its base address is sent to the called function. 50

More Related