1 Chapter 1 Data structure and Programming Principles.

51
1 Chapter 1 Data structure and Pr ramming Principles

Transcript of 1 Chapter 1 Data structure and Programming Principles.

Page 1: 1 Chapter 1 Data structure and Programming Principles.

1

Chapter 1 Data structure and Programming Principles

Page 2: 1 Chapter 1 Data structure and Programming Principles.

2

Contents Points

What is Data Structure?

General process of processing problems by computer.

Program Design in C++.

Example demonstration.

Page 3: 1 Chapter 1 Data structure and Programming Principles.

3

1 What is Data Structure?Fundamental Terms

Data Layers:Data (数据): a set of all the symbols that computer can manage.( 所有能输入到计算机中并被计算机所识别和处理的符号的总称。 )

Data Elements (数据元素) : 数据中的一个个体。 a character ‘*’ or a student when it is stored in a computer.

Data Item (数据项) :when the data element is a record,it can be divided into data items. Example:a student record may be combined by number, name, score and so on .

Page 4: 1 Chapter 1 Data structure and Programming Principles.

4

Data Structure: Collection of relational Data Elements

Logical Structure (逻辑结构) the intrinsic relations between data elementsAccording to the difference of the relation ,we can classify them into four kinds.

Lists

Trees

Graphics

Set

Page 5: 1 Chapter 1 Data structure and Programming Principles.

5

What is Data Structure?

Storage Structure: (存储结构) Physical Structure in computer

Contiguous structure

Linked structure

Page 6: 1 Chapter 1 Data structure and Programming Principles.

6

2 Processing problems by computer

algorithm

implement

Outside representation

ManagementDemand

Logical structure

Basic operation

Storage structure

question Mathematic model

Build

model

refine

Page 7: 1 Chapter 1 Data structure and Programming Principles.

7

Fundamental Tasks: Definition of Data Structure (including logical struc

ture and base operations); Realization of Data Structure (including storage str

ucture and base operations); Estimation and selection of Data Structure (analysi

s of algorithms) Asymptotic Time Complexity (时间复杂度) Asymptotic Space Complexity (空间复杂度)

Processing problems by computer

Page 8: 1 Chapter 1 Data structure and Programming Principles.

8

Problems of Large Programs

1. Problem specification (需求分析)

2. Program organization

3. Choice of data structures

4. Algorithm analysis

5. write the whole program

6. Debugging

7. Testing and verification

8. Maintenance

The patchwork approach is doomed to fail.

And we must also be careful to observe important principles of program design.

Page 9: 1 Chapter 1 Data structure and Programming Principles.

9

3 Program Design in C++

C++ features: Data Abstraction (数据抽象) Object-oriented design (面向对象的设计) Top-down approach Code reuse (代码重用) Refinement, improvement, extension of C

Introduction of OO (Object Oriented) Encapsulation (封装性) Inheritance (继承性) Polymorphism (多态性)

Page 10: 1 Chapter 1 Data structure and Programming Principles.

10

4 Example demonstration——game of life

Definition It takes place on an unbounded rectangular grid in

which each cell can either be occupied by an organism or not.

Occupied cells are called alive; unoccupied cells are called dead.

Which cells are alive or not changes from generation to generation according to the number of neighboring cells that are alive, as follows:

4.1 Rules for the game of life

Page 11: 1 Chapter 1 Data structure and Programming Principles.

11

Rules of the Game of life

1.The neighbors of a given cell are the eight cells that touch it vertically, horizontally, or diagonally. Every cell is either living or dead. (only two states)

2.A living cell stays alive in the next generation if it has either 2 or 3 living neighbors; it dies if it has 0, 1, 4, or more living neighbors. (for a living cell, conditions of still living and die)

Page 12: 1 Chapter 1 Data structure and Programming Principles.

12

Rules of the Game of life

3.A dead cell becomes alive in the next generation if it has exactly three neighboring cells, no more or fewer, that are already alive. All other dead cells remain dead in the next generation. (for a dead cell when the state will be change?)

4.All births and deaths take place at exactly the same time, so that a dying cell can help to give birth to another, but cannot prevent the death of others by reducing overcrowding, nor can cells being born either preserve or kill cells living in the previous generation. (interaction each other)

Page 13: 1 Chapter 1 Data structure and Programming Principles.

13

•A particular arrangement of living and dead cells in a grid is called a configuration.

•Applying the preceding rules, an initial configuration changes to another at each generation.

configuration

Page 14: 1 Chapter 1 Data structure and Programming Principles.

14

4.2Examples

Moribund example By rule 2 and 3, the

living cells will die in the coming generation, and no cells will become alive, so the configuration dies out

Page 15: 1 Chapter 1 Data structure and Programming Principles.

15

Stable example Each of the living cells

has a neighbor count of three, and hence remain alive, but the dead cells all have neighbor counts of two or less, and hence none of them becomes alive.

Examples --2

Page 16: 1 Chapter 1 Data structure and Programming Principles.

16

Alternate examples:The two configurations continue to alternate from generation to generation .

Examples --3

Page 17: 1 Chapter 1 Data structure and Programming Principles.

17

Variety( 多样化 ) : through many generation,a simple initial configuration grow into large configurations, die out, reach a state where they do not change Go through a repeating pattern every few generations.

Popularity (流行) :the life game is very popular.

Our goal:write a program that will show how an initial configuration will change from generation to generation .

Page 18: 1 Chapter 1 Data structure and Programming Principles.

18

4.3 the solution:classes ,objects,and methods

Set up a Life configuration as an initial arrangement of living and dead cells.

Print the Life configuration. While the user wants to see further generations:

Update the configuration by applying the rules of the Life game.

Print the current configuration.

Page 19: 1 Chapter 1 Data structure and Programming Principles.

19

Review of C++ elementsA class collects data and the methods used to access or change the data.

Such a collection of data and methods is called an object belonging to the given class.

Every C++ class consists of members that represent either variables (called data members) or functions (called methods or member functions). The member functions of a class are normally used to access or alter the data members.

Example:

For the Life game, Class:life classObject:a configurationMethod:initialize(),update(),print()

Page 20: 1 Chapter 1 Data structure and Programming Principles.

20

By relying on its specifications, a client can use a method without needing to know how the data are actually stored or how the methods are actually programmed. This important programming strategy known as information hiding.

Data members and methods available to a client are called public; further private variables and functions may be used in the implementation of the class, but are not available to a client.

Convention (约定)Methods of a class are public.

Functions in a class are private.

Review of C++ elements

Page 21: 1 Chapter 1 Data structure and Programming Principles.

21

4.4 Life: The Main Program#include “utility.h” //page 678-679

#include “life.h“//life 类的定义部分

int main( ) // Program to play Conway's game of Life.

/*Pre: The user supplies an initial configuration of living cells.

Post: The program prints a sequence of pictures showing the changes in the configuration of living cells according to the rules for the game of Life.

Uses: The class Life and its methods initialize( ) ,print( ) , and update( ) .The functions instructions( ) ,user_ says_ yes( ) . */

Page 22: 1 Chapter 1 Data structure and Programming Principles.

22

{

Life configuration;

instructions( );

configuration.initialize( );

configuration.print( );

cout << "Continue viewing new generations? " << endl;

while (user_says_yes( )) {

configuration.update( );

configuration.print( );

cout << "Continue viewing new generations? " << endl;

}

}

Page 23: 1 Chapter 1 Data structure and Programming Principles.

23

Utility Package We shall assemble a utility package that contains

various declarations and functions that prove useful in a variety of programs, even though these are not related to each other as we might expect if we put them in a class.

For example, we shall put declarations to help with error processing in the utility package.

Our first function for the utility package obtains a yes-no response from the user:

bool user_says_ yes( )Pre: None.Post: Returns true if the user enters ‘y’ or ‘Y’; returns false if the user enters ‘n’ or ‘N’; otherwise requests new response

Page 24: 1 Chapter 1 Data structure and Programming Principles.

24

Clients, that is, user programs with access to a particular class, can declare and manipulate objects of that class.

For example:declare a Life object by: Life configuration;

member selection operator We can now apply methods to work with configuration, using the C++ operator. For example, we can print out the data in configuration by writing:

configuration.print( );

The specifications of a method, function, or program are statements of precisely what is done. Preconditions state what is required before; postconditions state what has happened when the method, function, or program has finished.

Programming PreceptInclude precise specifications

with every program, function, and method that you write.

Other C++ elements

Page 25: 1 Chapter 1 Data structure and Programming Principles.

25

Programming Style( 自学 page 10-20)

Names (命名) : Guidelines of names: see p11-12Documentation and Format (文档化和书写格式)

oSome commonly accepted guidelines: see p13

Refinement and Modularity (求精和模块化) :oTop-down refinement

Page 26: 1 Chapter 1 Data structure and Programming Principles.

26

oAs we write the main program ,we decide exactly how the work will be divided among them.,how to divide the work?

自学

Page 27: 1 Chapter 1 Data structure and Programming Principles.

27

o Data Categories Input parameters--passed by value or by referen

ce(const) Output parameters—passed by reference (sugge

st) Inout parameters---used for both input and outp

ut Local variables—defined in the function and exis

t only while the function is being executed.Global variables----dangerous,cause side effect

Page 28: 1 Chapter 1 Data structure and Programming Principles.

28

Page 29: 1 Chapter 1 Data structure and Programming Principles.

29

4.5 Coding, Testing and Further Refinement

Coding (编码) :writing an algorithm in the correct syntax of a computer language like C++Testing (测试) :running the program on sample data chosen to find errorsFurther Refinement (进一步细化) :turn to the functions not yet written and repeat these steps

Page 30: 1 Chapter 1 Data structure and Programming Principles.

30

Example demonstration——game of life

Coding1.Stubs (占位程序)

compile each function and class separatelyto compile the main program correctly, there must be something in the place of each function that is used, so put in short, dummy functions.——which named stubsthe simplest stubs are those that do little or nothing at all:

void instruction() {}

bool user_says_yes() { return false;}

Page 31: 1 Chapter 1 Data structure and Programming Principles.

31

Coding of game of life2.Definition of the class Life

const int maxrow=20,maxcol=60; //living cells 共有 20 行, 60 列class Life{ // 存放在 *.h 文件中的类体声明public:

void initialize(); // 初始化 living cells 的状态void print(); // 打印输出当前 living cells 的状态void update(); // 进行 deadliving 间的转换

private:

int grid[maxrow+2][maxcol+2]; // 借助两维数组存放 living cells

// 注意:为处理一致,添加了虚拟的 2 行 2 列,放围墙int neighbor_count(int row,int col); // 统计邻居 cell 的状态

};

Page 32: 1 Chapter 1 Data structure and Programming Principles.

32

Stub example2:To check if the class definition is correct,We should supply the following stubs for its methods in life.cpp:

void Life :: initialize( ) {}void Life :: print( ) {}void Life :: update( ) {}

Page 33: 1 Chapter 1 Data structure and Programming Principles.

33

Instructionsvoid instructions( )/* Pre: None.Post: Instructions for using the Life program have been printed. */{cout << "Welcome to Conway’s game of Life." << endl;cout << "This game uses a grid of size "

<< maxrow << " by " << maxcol << " in which each" << endl;cout << "cell can either be occupied by an organism or not." << endl;cout << "The occupied cells change from generation to generation"<< en

dl;cout << "according to how many neighboring cells are alive."<< endl;}

Page 34: 1 Chapter 1 Data structure and Programming Principles.

34

User_says_yes( )bool user says yes( ){

int c;bool initial response = true;do { // Loop until an appropriate input is received.if (initial_response)

cout << " (y,n)? " << flush;else

cout << "Respond with either y or n: " << flush;do { // Ignore white space.

c = cin.get( );} while (c == ‘\n’ || c == ‘ ’ || c == ‘\t’);

initial_response = false;} while (c != ‘y‘ && c != ‘Y‘ && c != ‘n‘ && c != ‘N‘);return (c == ‘y‘ || c == ‘Y‘);}

Page 35: 1 Chapter 1 Data structure and Programming Principles.

35

Functions and Methods of class Life

3.Counting neighbors: sentinel (岗哨) (hedge):A sentinel is an extra entry put i

nto a data structures so that boundary conditions need not be treated as a special case.

int Life::neighbor_count(int row,int col){int i,j,count=0;for (i=row-1;i<=row+1;i++)

for (j=col-1;j<=col+1;j++)count+=grid[i][j];// 如果存活,则累加;否则为 0

count-=grid[row][col]; // 去除自己return count;

}

Page 36: 1 Chapter 1 Data structure and Programming Principles.

36

Page 37: 1 Chapter 1 Data structure and Programming Principles.

37

Functions and Methods of Class Life

4.Updating the gridvoid Life::update(){

int row,col,new_grid[maxrow+2][maxcol+2];for (row=1;row<=maxrow;row++)

for (col=1;col<=maxcol;col++) switch(neighbor_count(row,col)){// 调用统计函数 , 按结果分情

况 case 2: new_grid[row][col]=grid[row][col]; break;// 不变 case 3: new_grid[row][col]=1; break; // 激活 default: new_grid[row][col]=0; //dead }

for (row=1;row<=maxrow;row++)for (col=1;col<=maxcol;col++) grid[row][col]=new_grid[row][col];// 将临时数组中的数据拷贝回

原 grid 数组}

Page 38: 1 Chapter 1 Data structure and Programming Principles.

38

Functions and Methods of Class Life

5.Input and Output:

Page 39: 1 Chapter 1 Data structure and Programming Principles.

39

Functions and Methods of Class Life Input——initialize

void Life::initialize(){int row,col;for (row=0;row<=maxrow+1;row++) for (col=0;col<=maxcol+1;col++)

grid[row][col]=0;cout<<“List the coordinates for living cells.”<<endl;cout<<“Terminate the list with the special pair (-1,-1)”<<en

dl;cin>>row>>col;while (row!=-1||col!=-1){ if (row>=1&&row<=maxrow)

if (col>=1&&col<=maxcol) grid[row][col]=1;else cout<<“Column “<<col<<“ is out of range.”<<e

ndl; else cout<<“Row “<<row<<“ is out of range.”<<endl; cin>>row>>col;}

}

Page 40: 1 Chapter 1 Data structure and Programming Principles.

40

Functions and Methods of class Life

Output——print:void Life::print(){

int row,col;cout<<“\nThe current Life configuration is: “<<endl;for (row=1;row<=maxrow;row++){

for (col=1;col<=maxcol;col++) if (grid[row][col]==1) cout<<“ * ”; else cout<<“ ”; cout<<endl;}cout<<endl;

}}

Page 41: 1 Chapter 1 Data structure and Programming Principles.

41

Functions and Methods of Class Life

6.Drivers: Driver is a short auxiliary program whose

purpose is to provide the necessary input for the function, and evaluate the result——so that each function can be isolated and studied by itself

Page 42: 1 Chapter 1 Data structure and Programming Principles.

42

Example 1:driver for neighbor_ count():int main ( ) // driver for neighbor_count( )/* Pre: None.Post: Verifies that the method neighbor_count ( ) if it returns the correct values.Uses: The class Life and its method initialize( ) . */{

Life configuration;configuration.initialize( );for (row = 1; row <= maxrow; row++) { for (col = 1; col <= maxrow; col++)

cout << configuration.neighbor_count(row, col) << " "; cout << endl;

}}

Page 43: 1 Chapter 1 Data structure and Programming Principles.

43

Example 2 :driver for initialize() and print():Sometimes two functions can be used to check each other.

configuration.initialize( );configuration.print( );

Both methods can be tested by running this driver and making sure that the configuration printed is the same as that given as input.

Page 44: 1 Chapter 1 Data structure and Programming Principles.

44

7.Methods for debugging: (self-study)

1). Structured walkthrough

2). Trace tools and snapshots

3). Scaffolding

4). Static analyzer

Page 45: 1 Chapter 1 Data structure and Programming Principles.

45

Example demonstration——game of life

8.Test(self-study)Principles of program Testing:

Black-Box Method (黑盒法)(a) Easy values(b) Typical, realistic values(c) Extreme values(d) Illegal values

Glass-Box Method (白盒法) : Trace all the paths through theProgram,for a single small method, it is an excellent debugging an

d test methodTicking-Box Method——Don't do anything Just hope for the best!

Page 46: 1 Chapter 1 Data structure and Programming Principles.

46

Action:

In practice, black-box testing is usually more effective in uncovering errors. One reason is that most subtle programming errors often occur not within a function but in the interface between functions, in misunderstanding of the exact conditions and standards of information interchange between function.

Page 47: 1 Chapter 1 Data structure and Programming Principles.

47

Example demonstration——game of life

Program Maintenance (self-study)

For a large and import program, more than half the work comes in the maintenance phase, after it has been completely debugged, tested, and put into use.First step of program maintenance is to begin the continuing process of review, analysis, and evaluation. (for some useful question, see p34)

Page 48: 1 Chapter 1 Data structure and Programming Principles.

48

Example demonstration——game of life

Program MaintenanceReview of the Life program

problem specification (问题规范)program correctness (程序纠错)user interface (用户接口)modularity and structure (模块化与结构化)documentation (文档)efficiency (效率)

Program revision and redevelopment (修订与发布)

Page 49: 1 Chapter 1 Data structure and Programming Principles.

49

Pointers and Pitfalls 1. To improve your program, review the logic. Don't

optimize code based on a poor algorithm. 2. Never optimize a program until it is correct and

working. 3. Don't optimize code unless it is absolutely

necessary. 4. Keep your functions short; rarely should any

function be more than a page long. 5.Be sure your algorithm is correct before starting to

code. 6. Verify the intricate parts of your algorithm.

Page 50: 1 Chapter 1 Data structure and Programming Principles.

50

本章习题

P10 Exercise1.2 (a)(e)(I) P17 Exercise1.3 E1(a)(d) E2 E9 P32 Exercise1.4 E1 P38 Exercise1.5 E1 E2

P32 Programming projects 1.4 P39 Programming projects 1.5 p1-p5

Page 51: 1 Chapter 1 Data structure and Programming Principles.

51

Algorithm and program Description of the particular steps of the process of a problem( 处理

某一问题的步骤的描述 ) characteristics

Finity Certainty Feasibility Input interface Output interface

Format is flexible , it can be described by Natural Language, Advanced Language ,and the syntax is not the most important thing,

Nothing to do with the environment The whole process of the problem (用计算机处理问题的全部代码的整

体) Infinity Syntax must be accurate Closely linked with the environment