You are on page 1of 30

Computer Programming and Basic Software Engineering

4. Program Design and Debugging

START
Display message
How many
hours did you
work?

What is a Flowchart?

Read Hours

A flowchart is a diagram that


depicts the flow of a program.

The figure shown here is a


flowchart for the pay-calculating
program.

Display message
How much do
you get paid per
hour?

Read PayRate

Multiply Hours
by PayRate.
Store result in
GrossPay.

Display
GrossPay

END

Computer Programming and Basic Software Engineering


4. Program Design and Debugging
START

Basic Flowchart Symbols


z

Notice there are three types


of symbols in this
flowchart:

rounded rectangles
parallelograms
a rectangle

Rounded
Rectangle

Display message
How many
hours did you
work?

Read Hours

Display message
How much do
you get paid per
hour?

Read PayRate

Each symbol represents a


Rectangle
different type of operation.

Rounded
Rectangle

Multiply Hours
by PayRate.
Store result in
GrossPay.

Display
GrossPay

END

Parallelogram

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

START

Basic Flowchart Symbols


z

Terminal

Display message
How many
hours did you
work?

Terminals

Read Hours

represented by rounded
rectangles
indicate a starting or
ending point

Display message
How much do
you get paid per
hour?

Read PayRate

START

Multiply Hours
by PayRate.
Store result in
GrossPay.

END
Terminal

Display
GrossPay

END

Computer Programming and Basic Software Engineering


4. Program Design and Debugging
START

Basic Flowchart Symbols


z

Input/Output Operations

represented by
parallelograms
indicate an input or output
operation

Display message
How many
hours did you
work?
4

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.

Read Hours

Display
GrossPay

END

Input/Output
Operation

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

START

Basic Flowchart Symbols

Display message
How many
hours did you
work?

Read Hours

Screen Output

How many
hours did
you work?

Step 1: An
Output
Operation

Display message
How much do
you get paid per
hour?

Read PayRate

Multiply Hours
by PayRate.
Store result in
GrossPay.

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

Display
GrossPay

END

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

START

Basic Flowchart Symbols


How many
hours did
you work?
40

Step 2: An Input
Operation
(User types 40)

Display message
How many
hours did you
work?

Read Hours

Display message
How much do
you get paid per
hour?

Read PayRate

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

Multiply Hours
by PayRate.
Store result in
GrossPay.

The value 40 is stored in


Hours.

Display
GrossPay

END

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

START

Basic Flowchart Symbols


z

Display message
How many
hours did you
work?

Processes

Read Hours

represented by rectangles
indicates a process such as a
mathematical computation or
variable assignment

Display message
How much do
you get paid per
hour?

Read PayRate

Multiply Hours
by PayRate.
Store result in
GrossPay.

Process

Multiply Hours
by PayRate.
Store result in
GrossPay.

Display
GrossPay

END

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Connectors
z
z

Sometimes a flowchart will not fit on one page.


A connector (represented by a small circle) allows
you to connect two flowchart segments.

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

START

END
A

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Modules
z

A program module (such as a function in C++) is


represented by a special symbol.
START

The position of the module


symbol indicates the point the
module is executed.
A separate flowchart can be
constructed for the module.

Read Input.

Call calc_pay
function.

Display results.

END

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Sequence Structure
z
z

10

A series of actions are performed in sequence


The pay-calculating example was a sequence
flowchart.

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Decision Structure
z

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

NO

YES

11

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Decision Structure
z

The flowchart segment below shows how a decision


structure is expressed in C++ as an if/else statement.
Flowchart
NO

C++ Code
YES

x < y?

if (x < y)
a = x * 2;
else

Calculate a
as x plus y.

12

Calculate a
as x times 2.

a = x + y;

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Decision Structure
z

The flowchart segment below shows a decision


structure with only one action to perform. It is
expressed as an if statement in C++ code.
Flowchart
NO

C++ Code
YES

x < y?

if (x < y)
a = x * 2;

Calculate a
as x times 2.

13

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Repetition Structure
z
z

14

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.

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Repetition Structure
z

The flowchart segment below shows a repetition


structure expressed in C++ as a while loop.
Flowchart

C++ Code
while (x < y)
x++;

YES
x < y?

Add 1 to x

15

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

A Post-Test Repetition Structure


z
z
z

16

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

YES
x < y?

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

A Post-Test Repetition Structure


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

C++ Code

Display x
do
{

Flowchart

cout << x << endl;


x++;
} while (x < y);

Add 1 to x

YES
x < y?

17

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Case Structure
z

One of several possible actions is taken, depending on the


contents of a variable.

The structure below indicates actions to perform depending


on the value in years_employed.

CASE
years_employed

1
bonus = 100

18

bonus = 200

bonus = 400

Other
bonus = 800

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Combining Structures
z

This flowchart segment


shows two decision
structures combined. NO

YES
x > min?

Display x is
outside the limits.

NO

YES
x < max?

Display x is
outside the limits.

19

Computer Programming and Basic Software Engineering


4. 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 structural
method for program
development.
20

Display x is
within limits.

Computer Programming and Basic Software Engineering


4. 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 small
programs and debug them independently.
Divide and Conquer
Difficulty in
debugging

Program size
21

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

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().

int
int main()
main()
{{
::
::
::
::
::
::
}}
22

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

Computer Programming and Basic Software Engineering


4. 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.

23

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

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().
#include <iostream>
using namespace std;
bool menu(); //function prototype
int main()
{
bool exitflag = false; //flag is bool
while (exitflag == false)
{
exitflag = menu();
}
return 0;
}
24

Computer Programming and Basic Software Engineering


4. 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.
25

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

For
For users
users

Documenting a Program - readme


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

26

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.

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

For
For developers
developers

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.

27

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

For example
Totally meaningless comment!
// The main function
int main()
{
cout << "Hello World!\n";
// cout Hello World
return 0;
// return a number 0
}

28

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Tell something hidden in the program!


// It is to demonstrate the basic structure of a C++
//
program
// Usage: HelloWorld
int main()
{
cout << "Hello World!\n";
// print the string Hello World! on screen
return 0;
// Indicate to the system the execution is
// successful
}

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

Computer Programming and Basic Software Engineering


4. 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)
30

Computer Programming and Basic Software Engineering


4. 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.
31

Computer Programming and Basic Software Engineering


4. 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.

32

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Case study
Developing a program step-by-step

33

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 of
them;
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.

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Step
Step 00 Prepare
Prepare
aa flowchart
flowchart

Start
D

Ask user to choose a, b or q

To better
visualize the
problem, we
may develop a
flowchart for it
Skeleton
Menu
34

Yes
User chooses a?

No
User chooses b?

Yes
B

No
User chooses q?

Yes

No
End

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

D
A

Input integers and


calculate the mean

Input integers and


calculate the variance

Generate error message

35

Computer Programming and Basic Software Engineering


4. 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 input
int main()
{
bool exitflag = false;
// A flag to indicate if user wants to quit
while (exitflag == false)
{
exitflag = menu();
// If user chooses 'q', menu() returns true
}
return 0;
}

Step
Step 11 construct
construct the
the
skeleton
skeleton

36

Computer Programming and Basic Software Engineering


4. 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
Just
Justenough
enough
for
the
for the
program
program
skeleton
skeletonto
to
compile
compileand
and
execute
execute

// A stub
// Input parameter: Nil
// Return parameter: Just a constant
bool menu()
{
return true; //Loop 1 time
}

37

Computer Programming and Basic Software Engineering


4. 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 input
int main()
{
:
So
:
Sothe
thewhole
wholeprogram
programat
atthis
thisstage
stageisis
return 0;
just
justlike
likethat
that
}
// A stub
// Input parameter: Nil
// Return parameter: Just a constant
bool menu()
{
return true;
}
38

Computer Programming and Basic Software Engineering


4. 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
39

Computer Programming and Basic Software Engineering


and Debugging
// Show4. Program
a menuDesign
to user
and ask for input
// Input: Nil
// Return: true if user chooses 'q', otherwise false
void average(char); // Ask for a series of numbers and
//
compute their mean or variance
bool 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() here
default : cout << "Wrong input!\n"; break;
}
return false;
}

40

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

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()
// A stub
// Input parameter: char command
//
if 'a', do mean; if 'b', do variance
// Return parameter: Nil
void average(char command)
{
}
41

Computer Programming and Basic Software Engineering


4. 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 average()
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 menu(), it is desirable to
further break a big function into smaller functions
Add stubs again when needed Divide and conquer
It is desirable to have each function contained at
most 20 lines of codes.
42

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

// Get positive nos., find mean or variance


// Input parameter: char command //
'a'-> mean; 'b'-> variance
// Return parameter: Nil
void average(char command)
{ double input = 0;// Store data input by user
double sum = 0; // Store temporary sum
int count = 0;
// Count no. of data entered
while (input >= 0)
// If negative no., quit
{
cout << "Please enter your data: ";
cin >> input;
if (input < 0) continue; // Leave average() on -ve input
count+=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
} }
43

Computer Programming and Basic Software Engineering


4. 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 record
b. Show all records
q. Quit

44

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

For every user command input, call a function. You dont


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.

45

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.

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Debugging a Program

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

46

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Compile-time 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

47

Once the first one is corrected, the rest may be


solved as well.

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Run-time Debugging

Can have no error message

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.
48

Computer Programming and Basic Software Engineering


4. 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)
Warnings
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).

A structured way in program development can


help avoid run-time errors

49

Never develop your program in one step


Always ensure the skeleton is correct before going
forward. Related to logic

Computer Programming and Basic Software Engineering


4. 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 runtime 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 checkpoints the program can correctly get through.
50

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

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 c
at different parts of
the program.
51

#include <iostream>
using namespace std;
int main()
{ int a, b, c;
cout << "Enter 3 numbers: \n";
cin >> a;
cout << a << endl; // Checkpoint
cin >> b;
cout << b << endl; // Checkpoint
cin >> c;
cout << c << endl; // Checkpoint
if (c = (a+b))
{
cout << a << endl << b
<< endl << c; // Checkpoint
cout << "c = a+b\n";
}
return 0;
}

The output tells which statements have been executed.

Computer Programming and Basic Software Engineering


4. 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
52

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Step 1:
Build the program of
interest
Click on the lines of
code where you would
like to set breakpoints
Right-click Breakpoint
Insert Breakpoint

53

Breakpoints:
Breakpoints:
The
Themoments
momentsthat
that
you
youwould
wouldlike
liketo
to
examine
examinethe
thestatus
statusof
of
the
theresource
resourceallocated
allocated
to
tothe
theproject
project

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

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

This
Thisline
lineof
ofcode
codeisis
to
tobe
beexecuted
executed
Status
Statuswindow:
window:
Give
Givethe
thevalue
valueof
of
all
related
all related
variables
variables
54

Autos displays variables used in


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

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Status
Statuswindow:
window:
One
Onecan
canalso
also
particularly
particularlywatch
watch
the
theresult
resultof
ofan
an
expression
expressionby
by
typing
typingititin.
in.

55

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Stop
Stopdebugging
debugging

Step
Step Out:
Out:
Return
Returnto
tothe
the
calling
function
calling function

Continue
Continue
debugging
debugging
until
untilthe
thenext
next
breakpoint
breakpoint
Step
Step Over:
Over:
Execute
Executejust
just
the
thecurrent
current
line
line

56

Check View Toolbars Debug


if you cannot see the debug toolbar.

Step
Step Into:
Into:Like
Like
Step
Step Over,
Over,but
butifif
the
thecurrent
currentstatement
statement
isisaafunction,
function,go
gointo
into
this
thisfunction
functionto
todebug
debug

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Step 3: Step
over the codes
On
Onstepping
steppingover
over
each
eachline
lineof
ofcode,
code,the
the
current
values
of
the
current values of the
variables
variablesare
areshown
shown

57

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Step 4: Find the


error
The
Theuser
userinputs
inputs2,
2,33
and
and44for
fora,
a,bband
andcc
respectively.
respectively.But
But
after
executing
after executingthe
theifif
statement,
statement,ccchanges
changes
to
to5.
5.Obviously
Obviouslythere
there
isisaaproblem
problemin
inthat
that
statement
statement

58

Using Step Over

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Step 5: Fix
the error
Stop
Stop
Debugging.
Debugging.
Go
Goback
backto
tothe
the
source
sourceand
andfix
fix
the
theerror
error

59

Computer Programming and Basic Software Engineering


4. Program Design and Debugging

Exercise 4.2
The Run-time Debugger
of Visual Studio can also
help us analyze the runtime 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
60

1
2
3
4
5
6
7
8
9
10
11
12
13

#include <iostream>
using namespace std;
int main()
{ int CurrentX;
int x = 50;
CurrentX = x;
{
int x = 100;
CurrentX = x;
}
CurrentX = x;
return 0;
}

You might also like