4. program design and debugging start what is a...

30
1 Computer Programming and Basic Software Engineering 4. Program Design and Debugging What is a Flowchart? z A flowchart is a diagram that depicts the “flow” of a program. z The figure shown here is a flowchart for the pay-calculating program. START Display message “How many hours did you work?” Read Hours Display message “How much do you get paid per hour?” Read PayRate Multiply Hours by PayRate. Store result in GrossPay. Display GrossPay END 2 Computer Programming and Basic Software Engineering 4. Program Design and Debugging z Notice there are three types of symbols in this flowchart: rounded rectangles parallelograms a rectangle z Each symbol represents a different type of operation. START Display message “How many hours did you work?” Read Hours Display message “How much do you get paid per hour?” Read PayRate Multiply Hours by PayRate. Store result in GrossPay. Display GrossPay END Rounded Rectangle Parallelogram Rectangle Rounded Rectangle Basic Flowchart Symbols

Upload: phamhanh

Post on 02-Apr-2018

225 views

Category:

Documents


1 download

TRANSCRIPT

1

Computer Programming and Basic Software Engineering4. Program Design and Debugging

What is a Flowchart?

A flowchart is a diagram that depicts the “flow” of a program.

The figure shown here is a flowchart for the pay-calculating program.

START

Display message “How many

hours did you work?”

Read Hours

Display message “How much do you get paid per

hour?”

Read PayRate

Multiply Hours by PayRate.

Store result in GrossPay.

Display GrossPay

END

2

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Notice there are three types of symbols in this flowchart:

– rounded rectangles

– parallelograms

– a rectangle

Each symbol represents a different type of operation.

START

Display message “How many

hours did you work?”

Read Hours

Display message “How much do you get paid per

hour?”

Read PayRate

Multiply Hours by PayRate.

Store result in GrossPay.

Display GrossPay

END

Rounded Rectangle

Parallelogram

Rectangle

Rounded Rectangle

Basic Flowchart Symbols

3

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Terminals– represented by rounded

rectangles

– indicate a starting or ending point

START

Display message “How many

hours did you work?”

Read Hours

Display message “How much do you get paid per

hour?”

Read PayRate

Multiply Hours by PayRate.

Store result in GrossPay.

Display GrossPay

END

Terminal

START

ENDTerminal

Basic Flowchart Symbols

4

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Basic Flowchart Symbols

Input/Output Operations– represented by

parallelograms

– indicate an input or output operation

START

Display message “How many

hours did you work?”

Read Hours

Display message “How much do you get paid per

hour?”

Read PayRate

Multiply Hours by PayRate.

Store result in GrossPay.

Display GrossPay

END

Display message “How many

hours did you work?”

Read Hours

Input/Output Operation

5

Computer Programming and Basic Software Engineering4. Program Design and Debugging

How many hours did you work?

START

Display message “How many

hours did you work?”

Read Hours

Display message “How much do you get paid per

hour?”

Read PayRate

Multiply Hours by PayRate.

Store result in GrossPay.

Display GrossPay

END

Variable Contents:Hours: ?PayRate: ?GrossPay: ?

Step 1: An Output Operation

Screen Output

Basic Flowchart Symbols

6

Computer Programming and Basic Software Engineering4. Program Design and Debugging

How many hours did you work?

40

START

Display message “How many

hours did you work?”

Read Hours

Display message “How much do you get paid per

hour?”

Read PayRate

Multiply Hours by PayRate.

Store result in GrossPay.

Display GrossPay

END

Variable Contents:Hours: 40PayRate: ?GrossPay: ?

Step 2: An Input Operation

(User types 40)

The value 40 is stored in Hours.

Basic Flowchart Symbols

7

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Processes– represented by rectangles

– indicates a process such as a mathematical computation or variable assignment

START

Display message “How many

hours did you work?”

Read Hours

Display message “How much do you get paid per

hour?”

Read PayRate

Multiply Hours by PayRate.

Store result in GrossPay.

Display GrossPay

END

Multiply Hours by PayRate.

Store result in GrossPay.

Process

Basic Flowchart Symbols

8

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Connectors

A

ASTART

END

The “A” connector indicates that the second flowchart segment begins where the first segment ends.

Sometimes a flowchart will not fit on one page.A connector (represented by a small circle) allows you to connect two flowchart segments.

9

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Modules

•The position of the module symbol indicates the point the module is executed.

•A separate flowchart can be constructed for the module.

START

END

Read Input.

Call calc_pay function.

Display results.

A program module (such as a function in C++) is represented by a special symbol.

10

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Sequence Structure

A series of actions are performed in sequence

The pay-calculating example was a sequence flowchart.

11

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Decision Structure

A new symbol, the diamond, indicates a yes/no question. If the answer to the question is yes, the flow follows one path. If the answer is no, the flow follows another path

YESNO

12

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Decision StructureThe flowchart segment below shows how a decision structure is expressed in C++ as an if/else statement.

YESNO

x < y?

Calculate a as x times 2.

Calculate a as x plus y.

if (x < y)

a = x * 2;

else

a = x + y;

Flowchart C++ Code

13

Computer Programming and Basic Software Engineering4. Program Design and Debugging

The flowchart segment below shows a decision structure with only one action to perform. It is expressed as an if statement in C++ code.

if (x < y)

a = x * 2;

Flowchart C++ Code

YESNO

x < y?

Calculate a as x times 2.

Decision Structure

14

Computer Programming and Basic Software Engineering4. Program Design and Debugging

A repetition structure represents part of the program that repeats. This type of structure is commonly known as a loop.

Notice the use of the diamond symbol. A loop tests a condition, and if the condition exists, it performs an action. Then it tests the condition again. If the condition still exists, the action is repeated. This continues until the condition no longer exists.

Repetition Structure

15

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Repetition Structure

The flowchart segment below shows a repetition structure expressed in C++ as a while loop.

while (x < y)

x++;

Flowchart C++ Code

x < y? Add 1 to xYES

16

Computer Programming and Basic Software Engineering4. Program Design and Debugging

This flowchart segment shows a post-test repetition structure.

The condition is tested AFTER the actions are performed.

A post-test repetition structure always performs its actions at least once.

Display x

Add 1 to x

YESx < y?

A Post-Test Repetition Structure

17

Computer Programming and Basic Software Engineering4. Program Design and Debugging

A Post-Test Repetition StructureThe flowchart segment below shows a post-test repetition structure expressed in C++ as a do-while loop.

do{

cout << x << endl;x++;

} while (x < y);

Flowchart

C++ CodeDisplay x

Add 1 to x

YESx < y?

18

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Case Structure

The structure below indicates actions to perform depending on the value in years_employed.

CASEyears_employed

1 2 3 Other

bonus = 100 bonus = 200 bonus = 400 bonus = 800

One of several possible actions is taken, depending on the contents of a variable.

19

Computer Programming and Basic Software Engineering4. Program Design and Debugging

This flowchart segment shows two decision structures combined.

Combining Structures

Display “x is within limits.”

Display “x is outside the limits.”

YESNOx > min?

x < max?

YESNO

Display “x is outside the limits.”

20

Computer Programming and Basic Software Engineering4. Program Design and Debugging

• Seldom do we have a program worked the first time it is written

• Need debugging

To find out and correct the errors in a program

• May need many times of iteration for a large program

• To reduce the number of iteration, need a structuralmethod for program development.

21

Computer Programming and Basic Software Engineering4. Program Design and Debugging

• Debugging a big program is exponentially more difficult than a small program

• If a big program is to be developed, always try to break it down to many smallprograms and debug them independently.

Divide and ConquerDifficulty in debugging

Program size

22

Computer Programming and Basic Software Engineering4. Program Design and Debugging

int main(){

::::::

}

int main(){

::::::

}

int main(){

:} int function1() { :}int function2(){ :}

int main(){

:} int function1() { :}int function2(){ :}

• It is a very bad habit to write a program in main() only

since it makes the program very big

• Always break it down by calling functions from main().

23

Computer Programming and Basic Software Engineering4. Program Design and Debugging

• Usually main() is only used to indicate the program flow. The actual task is done by the functions called by main()

• By looking at the sequence of functions called by main(), people basically understand what is going on in a program

• It gives the skeleton of a program.

24

Computer Programming and Basic Software Engineering4. Program Design and Debugging

#include <iostream>using namespace std;bool menu(); //function prototypeint main(){ bool exitflag = false; //flag is bool

while (exitflag == false){ exitflag = menu();}return 0;

}

• In the example program below, people expect this program will repeatedly show a menu

• If one is interested at the details of the menu, he can further read the function menu().

25

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Improve the Readability of Programs• In practice, the time a programmer spends in

documentation is more than writing the program

• A real program is never developed by a single person, co-operations are needed between programmers or even teams of programmers

• Besides, a program developed by a team of programmers often needs to be maintained by another team

• It is essential that a program is properly documented to allow team work.

26

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Documenting a Program - readme

• After developing a program, a readme file is often prepared in practice to indicate the following:

• Background information of the program (e.g. objectives, version no., development date, developer name)

• How to use the program (e.g. command line options)

• Additional resource required (e.g. hardware, driver, etc.)

• Bug fixed as compared to previous version(s)

• Possible conflict with other programs.

For usersFor users

27

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Within a program - comments

• Commenting a program is the responsibility of every programmer

• Need meaningful comments

Not explaining something people know already, but something people will have difficulty to understand.

For developersFor developers

28

Computer Programming and Basic Software Engineering4. Program Design and Debugging

// The main functionint main(){

cout << "Hello World!\n"; // cout Hello Worldreturn 0; // return a number 0

}

Totally meaningless comment!

• For example

29

Computer Programming and Basic Software Engineering4. Program Design and Debugging

// It is to demonstrate the basic structure of a C++ // program// Usage: HelloWorldint main(){

cout << "Hello World!\n"; // print the string Hello World! on screenreturn 0; // Indicate to the system the execution is // successful

}

Tell something hidden in the program!

See the lines for comments are more than the codesSee the lines for comments are more than the codes

30

Computer Programming and Basic Software Engineering4. Program Design and Debugging

How to comment?• At the beginning of each program, the following

comments are often required:

• Background information of the program(Objectives, version no., development date, developer name, etc.)

• Usage (e.g. command line options)

• Additional resource required (e.g. if any other projects/files are required for compiling this program, e.g. header files)

31

Computer Programming and Basic Software Engineering4. Program Design and Debugging

How to comment?

• At the beginning of each function, the following information is needed

• Objective of this function

• Other functions that it will call

• Passed parameters

• Return parameters

• Global variables that have been made use of.

32

Computer Programming and Basic Software Engineering4. Program Design and Debugging

How to comment?

• Inside a function, the following information is needed

• The use of every local variable

• Explanation of any tricky part that other people may have difficulty in understanding.

33

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Case study –Developing a program step-by-step

• Write a program that repeatedly asks the user to select one of the following three options:

1. On choosing ‘a’, ask the user to input a series of positive numbers and show the mean ofthem;

2. On choosing ‘b’, ask the user to input a series of positive numbers and show the variance of them;

3. On choosing ‘q’, quit the program.

34

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Step 0 – Prepare a flowchartStep 0 – Prepare a flowchart

Start

Yes

No

A

Ask user to choose a, b or q

• To better visualize the problem, we may develop a flowchart for it

Yes

No

D

No

Yes

C

B

End

User chooses a?

User chooses b?

User chooses q?Skeleton

Menu

35

Computer Programming and Basic Software Engineering4. Program Design and Debugging

A

D

C

B

Input integers and calculate the mean

Input integers and calculate the variance

Generate error message

36

Computer Programming and Basic Software Engineering4. Program Design and Debugging

// This program is to compute the mean or variance // of a series of positive numbers input by user// Usage: Mean_Var// Version: 1// Date: Feb 14, 2006// Author: Frank#include <iostream>using namespace std;bool menu();// Show a menu to user and ask for inputint main(){ bool exitflag = false;

// A flag to indicate if user wants to quitwhile (exitflag == false){ exitflag = menu();

// If user chooses 'q', menu() returns true}return 0;

}

Step 1 – construct the skeletonStep 1 – construct the skeleton

37

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Step 2 – Add stubs (i.e. just for testing)

• The above program cannot be compiled and executed since the required function menu() has not been implemented

• We need to ensure the skeleton is correct before we proceed to implement the functions – add stubs

// A stub// Input parameter: Nil// Return parameter: Just a constantbool menu(){

return true; //Loop 1 time}

Just enoughfor the program skeleton to compile and execute

Just enoughfor the program skeleton to compile and execute

38

Computer Programming and Basic Software Engineering4. Program Design and Debugging

// This program is to compute the mean and variance // of a series of positive numbers input by user// :#include <iostream>using namespace std;bool menu();// Show a menu to user and ask for inputint main(){ :

:return 0;

}// A stub// Input parameter: Nil// Return parameter: Just a constantbool menu(){ return true;}

So the whole program at this stage is just like that

So the whole program at this stage is just like that

39

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Step 3 – Implement Functions

• If the skeleton has been proved to be correct, start to implement functions

• The original comments may need to be updated when any change is made to the original codes as a result of the implementation of functions

• Similar to developing main(), it is desirable to further break a big function into smaller functions

• Add stubs again when needed

40

Computer Programming and Basic Software Engineering4. Program Design and Debugging// Show a menu to user and ask for input

// Input: Nil// Return: true if user chooses 'q', otherwise falsevoid average(char); // Ask for a series of numbers and

// compute their mean or variancebool menu(){ char choice; // To store the command of user

cout<<"[a] Mean\n"<<"[b] Variance\n"<<"[q] Quit\n";cout << "Please enter your choice: ";cin >> choice;switch (choice){ case 'a': average('a'); break;

case 'b': average('b'); break;case 'q': return true; // Shall quit menu() heredefault : cout << "Wrong input!\n"; break;

}return false;

}

41

Computer Programming and Basic Software Engineering4. Program Design and Debugging

// A stub// Input parameter: char command –// if 'a', do mean; if 'b', do variance// Return parameter: Nilvoid average(char command){}

• menu() cannot be compiled or executed since average() has not been implemented

• To ensure menu() is correct, we need to compile and execute it.

• To solve the problem, a stub is added for average()

42

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Step 4 – Implement the sub-functions

• If the major functions have been proved to be correct, start to implement sub-functions

• The original comments may need to be updatedwhen any change is made to the original codes as a result of the implementation of functions

• Similar to developing menu(), it is desirable to further break a big function into smaller functions

•Add stubs again when needed

• It is desirable to have each function contained at most 20 lines of codes.

Divide and conquer

average()

43

Computer Programming and Basic Software Engineering4. Program Design and Debugging

// Get positive nos., find mean or variance// Input parameter: char command -// 'a'-> mean; 'b'-> variance// Return parameter: Nilvoid average(char command){ double input = 0;// Store data input by user

double sum = 0; // Store temporary sumint count = 0; // Count no. of data enteredwhile (input >= 0) // If negative no., quit{ cout << "Please enter your data: ";

cin >> input;if (input < 0) continue; // Leave average() on -ve inputcount+=1;if (command == 'a') // calculate and show the current mean{ sum = sum + input;

cout<<"\n\nThe current mean is "<<sum/count<<endl;} else // calculate and show the current variance{ sum = sum + input*input;

cout<<"\n\nThe current variance is "<<sum/count<<endl;} // it is in fact not the real variance

} }

44

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Exercise 4.1

By following the steps as described above, you are requested to develop the skeleton of a personnel database program. The program should be a console application that repeatedly asks users to do one of the following in the main menu:

a. Enter/modify recordb. Show all records q. Quit

45

Computer Programming and Basic Software Engineering4. Program Design and Debugging

• For every user command input, call a function. You don’t need to implement the details of the functions, just do the following:• If user chooses ‘a’, show a message “Please enter record:” call a function and get back to the main menu.

• If user chooses ‘b’, show a message “All records are shown below” call a function and get back to the main menu.

• If user chooses ‘q’, show a message “Thank you. Goodbye!!!” and then the program will quit.

• Make sure your program follows the style as shown in the case study (Do NOT use main() to do everything)

• Make sure your program is commented appropriately using the method as described above.

46

Computer Programming and Basic Software Engineering4. Program Design and Debugging

• It is often NOT the case that a program can run correctly once it is developed

• Debugging is often a necessary procedure

• Debugging can be divided into the following two stages

1. Compile-time debugging (relatively easy)

Correct the errors owing to incorrect use of language syntax or unresolved references

2. Run-time debugging (often far more difficult)

Correct the errors owing to incorrect program logic or resource usage

e.g. Memory fault

Debugging a Program

47

Computer Programming and Basic Software Engineering4. Program Design and Debugging

• Compile-time errors can often be spotted out by the compiler

• The compiler is able to detect the approximate error location, but cannot be exact

• Also, the error messages generated are sometimes irrelevant

• When a series of error messages are found, always try to debug them starting from the first one

• Once the first one is corrected, the rest may be solved as well.

Compile-time Debugging

48

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Run-time Debugging• Comparing with compile-time errors, run-time

errors are more difficult to locate and correct

• Run-time errors are often caused by wrong programming logic or improper use of resources

• Run-time errors may sometimes lead to incorrect results or even system failure

• Even worst, some run-time errors give no observable problem but gradually damage the system or the database.

Can have no error message

49

Computer Programming and Basic Software Engineering4. Program Design and Debugging

How to avoid Run-time Errors?• C++ has many standard features to allow possible

run-time errors be detected during compile-time(will be covered throughout this course)

• A structured way in program development can help avoid run-time errors• Never develop your program in one step• Always ensure the skeleton is correct before going

forward.

Rule of thumb: Try your very best to enable the compiler to detect the errors for you (that is, to convert run-time errors to compile-time errors whenever allowable).

Warnings

Related to logic

50

Computer Programming and Basic Software Engineering4. Program Design and Debugging

How to Debug Run-time Errors?• The problem of run-time errors can be observed

only at run-time

• One has to run the program in order to debug run-time errors

• To debug run-time errors, the first thing that has to be done is to locate the errors

• Achieved by the divide and conquer approach

• The simplest way is to set some check-points in the program and to see how many check-points the program can correctly get through.

51

Computer Programming and Basic Software Engineering4. Program Design and Debugging

#include <iostream>using namespace std;int main(){ int a, b, c;

cout << "Enter 3 numbers: \n";cin >> a;cout << a << endl; // Checkpointcin >> b;cout << b << endl; // Checkpointcin >> c;cout << c << endl; // Checkpointif (c = (a+b)){

cout << a << endl << b << endl << c; // Checkpoint

cout << "c = a+b\n";}return 0;

}

• The program on the right was used in Exercise 3.3

• It has a run-time error in line 12

• To correctly locate that errors, four checkpoints are added to show the value of a, b, and cat different parts of the program.

The output tells which statements have been executed.

52

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Run-time Debugger of Visual Studio• To help in debugging more complicated run-time

errors, Visual Studio has provided a run-time debugger

• Allow line-by-line tracing of program codes

• Allow arbitrary breakpoint in a program

• Allow examination of the status of all resources at the breakpoints, such as• Data in memory• Data value of variables

• Allow monitoring of a particular resource of interest

53

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Step 1:Build the program of interest

Click on the lines of code where you would like to set breakpoints

Breakpoints:The moments that you would like to examine the status of the resource allocated to the project

Breakpoints:The moments that you would like to examine the status of the resource allocated to the project

Right-click → Breakpoint → Insert Breakpoint

54

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Step 2:Build it successfully.Start the debugger by clicking Debug →Start Debugging

Status window: Give the value of all related variables

Status window: Give the value of all related variables

This line of code is to be executed

This line of code is to be executed Autos displays variables used in

the current line of code and the preceding line of code.

55

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Status window: One can also particularly watchthe result of an expression by typing it in.

Status window: One can also particularly watchthe result of an expression by typing it in.

56

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Stop debuggingStop debugging

Continue debugging until the next breakpoint

Continue debugging until the next breakpoint

Step Over:Execute just the current line

Step Over:Execute just the current line

Step Into: Like Step Over, but if the current statement is a function, go into this function to debug

Step Into: Like Step Over, but if the current statement is a function, go into this function to debug

Step Out:Return to the calling function

Step Out:Return to the calling function

Check View → Toolbars → Debug if you cannot see the debug toolbar.

57

Computer Programming and Basic Software Engineering4. Program Design and Debugging

On stepping over each line of code, the current values of the variables are shown

On stepping over each line of code, the current values of the variables are shown

Step 3: Step over the codes

58

Computer Programming and Basic Software Engineering4. Program Design and Debugging

The user inputs 2, 3and 4 for a, b and crespectively. But after executing the if statement, c changes to 5. Obviously there is a problem in that statement

The user inputs 2, 3and 4 for a, b and crespectively. But after executing the if statement, c changes to 5. Obviously there is a problem in that statement

Step 4: Find the error

Using Step Over

59

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Stop Debugging. Go back to the source and fix the error

Stop Debugging. Go back to the source and fix the error

Step 5: Fix the error

60

Computer Programming and Basic Software Engineering4. Program Design and Debugging

Exercise 4.21 #include <iostream>2 using namespace std;3 int main()4 { int CurrentX; 5 int x = 50;6 CurrentX = x;7 {8 int x = 100;9 CurrentX = x;10 }11 CurrentX = x;12 return 0;13 }

• The Run-time Debugger of Visual Studio can also help us analyze the run-time behavior of our program

• For the program on the right, estimate the values of CurrentX before and after the 6th, 9th, and 11th

lines are executed

• Verify your solutions by using the Run-time Debugger