You are on page 1of 72

CS1101 : Programming Methodology

http://www.comp.nus.edu.sg/~cs1101
Heng Aik Koan
Office : s15-05-13
email: hengak@comp.nus.edu.sg

1
Lecture
Notes

2
Text Book

3
Important

Continuous assessment (CA): 60%


(Labs, tutorials, Tests, Quiz, Practical
exams).
Exam: 40%, format: Open Book
Explore CS1101s website, learn how to
use the IVLE system.

4
Chapter 1: Program Development

CONTENTS:

1.1. Problem Analysis and Specification


1.2. Design
1.3. Coding
1.4. Verification and Validation
1.5. Software Engineering

5
1.0. Introduction

q The computer has become an


indispensable tool in many areas. Its
applications are far too many to
enumerate:

E.g. Business and Finance


Industry Government
Medicine Entertainment
Science

q These and many other applications all


require the development of software.

6
q Although the problems themselves and
specific techniques used in their
solutions vary, there are several phases
or steps that are common in the
software development process:

Problem analysis and


specification
Design
Coding
Verification and validation
Maintenance

7
q In this chapter we begin by describing
and illustrating the first four steps of
this software life cycle, using three
problems, each of which can be solved
with a simple program.

q In the last section, we discuss the 5th


step, software maintenance, and also
some of the questions and
complications that software developers
face in real world applications.

8
1.1. Problem Analysis and
Specification

q Because the initial description of a


problem may be somewhat vague and
imprecise, the first step in the
development of a program to solve the
problem is to analyze the problem and
formulate a specification on it.

9
q This specification must include:

1. a description of the problems input


what information is given and
which items are important in solving
the problem.

2. Its output what information must


be produced to solve the problem.

q Input and Output are the two major


parts of the problems specification,
and for a problem that appears in a
programming text, they are usually not
too difficult to identify.
10
Problem 1: Calculating Revenue

X installs coaxial cable for Y company.


For each installation, there is a basic
charge of $25.00 and an additional
charge of $2.00 for each foot of cable.
During the month of January, X
installed a total of 263 yards of cable at
27 different locations. What was the
total revenue that X generated for the
month?

11
INPUT:
Basic service charge: $25.00
Unit cable cost: $2.00
Number of installations: 27
Yards of cable: 263

OUTPUT:
Revenue generated

12
q One important aspect of problem
analysis is generalization.

q The effort involved in later phases of


the problem-solving process demands
that the program eventually developed
be sufficiently flexible, that it solves
not only the given specific problem but
also any related problem of the same
kind with little, if any, modification
required.

13
INPUT:
Basic service charge
Unit cable cost
Number of installations
Yards of cable:

OUTPUT:
Revenue generated

14
Problem 2: Pollution indices

The level of air pollution in the city is


measured by a pollution index.
Readings are made at 12.00pm at three
locations: X, Y and Z, and at a
randomly selected location in a
residential area. The average of these
three readings is the pollution index,
and a value of 50 or greater for this
index indicates a hazardous condition,
whereas values lower than 50 indicates
a safe condition.
15
INPUT:
Three pollution readings
Cutoff value to distinguish between
safe and hazardous condition

OUTPUT:
Pollution index
Condition: safe or hazardous

16
Problem 3: Mean Time to failure

One important statistic that is used in


measuring the reliability of a
component in a circuit is the mean time
to failure, which can be used to predict
the circuits lifetime.

As part of this evaluation, an engineer


tested several of these circuits and
recorded the time at which each failed.
We wish to develop a program to
process the data and determine the
mean time to failure.

17
INPUT
A collection of numeric values
(number unknown)

OUTPUT
The number of values
The mean of the values

18
1.2. Design

q Once the specification of a problem has


been given, a design plan for
developing a program or a system of
programs that meet the specification
must be formulated.

q Two important aspects of design are:


1. Selecting appropriate structures to
organize and store the data to be
processed, and

2. Designing procedures to process the


data.
19
q Because the computer is a machine
possessing no inherent problem-solving
capabilities, the procedures developed
to solve a problem must be formulated
as a detailed sequence of simple steps.
Such procedures are called algorithms.

q The steps that comprise an algorithm


must be organized in a logical and clear
manner so that the program that
implements this algorithm will be
similarly well structured.

20
q Structured algorithms and programs are
designed using three basic methods of
controls:

1. Sequential: Steps are performed in a


strictly sequential
manner, each step
being executed exactly
once.

2. Selection: One of a number of


alternative actions is
selected and executed.

3. Repetition: One or more steps are


performed repeatedly. 21
q These three structures are individually
quite simple, but in fact they are
sufficiently powerful that any
algorithm can be constructed using
them.

q Programs to implement algorithms


must be written in a language that the
computer can understand

22
It is therefore natural to describe
algorithms in a language that
resembles that used to write computer
programs. That is, in a
pseudoprogramming language or
pseudocode

There is no set of rules that precisely


define pseudocode. It varies from one
programmer to another.

23
Pseudocode is a mixture of natural
language and symbols, terms and
other features commonly used in
high-level languages.

The structure of an algorithm may be


displayed in a structure diagram that
shows the various tasks that must be
performed and their relation to one
another.

24
Algorithm for Revenue Calculation
Sequential Structure
(* Input : A basic ServiceCharge,
a UnitCost for cable,
number of Installation, and
YardsOfCable used.
Purpose: This algorithm calculates the
revenue generated by the
installation of a certain number of
yards of cable at a number of
locations. For each installation
there is a fixed basic service
charge and an additional charge for
each foot of cable.
Output: Revenue generated. *) 25
1. Enter ServiceCharge, UnitCost,
Installation,and YardsOfCable.
2. Calculate
FeetOfCable = 3 * YardsOfCable
3. Calculate
Revenue= Installation * ServiceCharge
+ UnitCost * FeetOfCable
4. Display Revenue

26
Algorithm for Pollution Index
problem : Selection Structure
(* Input : Three pollution levels and
a cutoff value.

Purpose: This algorithm reads three


pollution levels, Level1, Level2,
Level3, and a Cutoff value, It then
calculates the pollution Index. If the
value of Index is less than Cutoff, a
message indicating a safe condition is
displayed; otherwise, a message
indicating a hazardous condition is
displayed.
Output: The pollution Index and a
message indicating the air quality. 27
*)
1. Enter Level1, Level2, Level3 and
Cutoff.
2. Calculate
Index = (Level1 + Level2 +
Level3) / 3
3. Display Index.
4. If Index < Cutoff then
display Safe condition
else
display Hazardous condition

28
Algorithm to Calculate Mean Time to
Failure Repetition Structure

(* Input : A collection of failure times.

Purpose:This algorithm reads failure times,


count them, and find the mean time to
failure (MeanFailTime). FailTime
represents the current failure time entered,
NumTimes is the number of failure times,
and Sum is their sum. Values are read unitl
an end-of-data flag is encountered.

Output: MeanFailTime and NumTimes. *)

29
1. Initialize NumTimes to 0 and Sum to
0.0.
2. Enter the first value for FailTime.
3. While FailTime is not the end-of-data-
flag, do the following:
a. Increment NumTimes by 1.
b. Add FailTime to Sum.
c. Enter next value for FailTime.
4. If NumTimes 0 then
a. Calculate
MeanFailTime=Sum/NumTimes
b. Display MeanFailTime and
NumTimes.
else
display a No Data message.
30
1.3. Coding

q Coding is the process of implementing


in some programming language the
variable (structures) used to store the
data and the algorithms for solving
the problem.

q The program that implements that


algorithm must be written in the
vocabulary of a programming
language and must conform to the
syntax, or grammatical rules of the
language.

31
For Example, in Java:

Variables
Type
Operations
Input/Output
Comments
Program Composition

32
import java.io.*;

// input: basic service charge, cost per foot


// of cable, No of installation,and yards
// of cable are input to the program
// purpose: Program to calculate the revenue
// generated by an employee installing
// coaxial cable
// Output: User prompt and revenue generated
class Revenue {
public static void main (String [] args)
throws IOException {
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
String my_string;
int installations;
int yardsOfCable;
int feetOfCable;
int serviceCharge = 0;
int unitCost; 33
double revenue;
// Read the data

System.out.print("Enter Service Charge : ");


System.out.flush();
my_string = stdin.readLine();
serviceCharge = Integer.parseInt (my_string);

System.out.print("Enter no of installations : ");


System.out.flush();
my_string = stdin.readLine();
installations = Integer.parseInt (my_string);

System.out.print("Enter yards of cable : ");


System.out.flush();
my_string = stdin.readLine();
yardsOfCable = Integer.parseInt (my_string);

34
// perform the calculations

feetOfCable = 3 * yardsOfCable;
revenue = serviceCharge * installations
+ unitCost * feetOfCable;

// output the results

System.out.println ("Revenue generated "


" = " + revenue);

}
}

35
import java.io.*;

// Input: A collection of failure times


// Purpose: Algorithm to read failure times,
// count them, and find the mean
// time to failure (MeanFailTime).
// FailTime represents the current
// failure time entered, NumTimes
// if he number of failure. Values
// are read until end_of_data Flag
// is encountered.
// Output: MeanFailTime and NumTimes.

36
class Failure {
static final int end_of_data = 999;

public static void main (String [] args)


throws IOException {

BufferedReader stdin =
new BufferedReader
(new InputStreamReader(System.in));

String my_string;
int FailTime;
double Sum = 0.0;
int NumTimes = 0;
double MeanFailTime;

37
System.out.print ("enter first value ");
System.out.print (" of fail time: ");
System.out.flush();
my_string = stdin.readLine();
FailTime = Integer.parseInt (my_string);

// A loop to read in some data


// until end_of_data

while (FailTime != end_of_data) {


NumTimes = NumTimes + 1;
Sum = Sum + FailTime;
System.out.print (
"Read in next fail time +
"(999 to stop) : ");
System.out.flush();
my_string = stdin.readLine();
FailTime = Integer.parseInt(my_string);
}
38
// To calculate the mean of failure
// if there is input data

if (NumTimes != 0)
{ MeanFailTime = Sum / NumTimes;
System.out.println ("The number of +
failure times = " +
NumTimes);
System.out.println ("The mean of " +
" failure = " +
MeanFailTime);
}
else
System.out.println("No Data Input");
}
}

39
import java.io.*;

// input: Three pollution levels and a


// cutoff value
// purpose: This program reads 3 pollution
// levels and a cutoff value. It then
// calculate the pollution index.
// If the value of Index is less than
// Cutoff a message indicating
// a safe condition is displayed;
// otherwise a message
// indicating a hazadous condition
// is displayed
// Output: The pollution index and a message
// indicating the air quality.

40
class Pollution {

public static void main (String [ ] args)


throws IOException {

BufferedReader stdin = new BufferedReader


(new InputStreamReader (System.in));
String my_string;
int Level1;
int Level2;
int Level3;
int Cutoff;
double Index;

41
// Input three pollution levels

System.out.print("Pollution Level 1 : ");


System.out.flush( );
my_string = stdin.readLine( );
Level1 = Integer.parseInt (my_string);

System.out.print("Pollution Level 2 : ");


System.out.flush( );
my_string = stdin.readLine( );
Level2 = Integer.parseInt (my_string);

42
System.out.print("Pollution Level 3 : ");
System.out.flush( );
my_string = stdin.readLine( );
Level3 = Integer.parseInt (my_string);

System.out.print("Cutoff value : ");


System.out.flush( );
my_string = stdin.readLine( );
Cutoff = Integer.parseInt (my_string);

43
// To determine the index

Index = (Level1 + Level2 + Level3) / 3;


System.out.println("The index is : " + Index);

// Checking the condition

if (Index < Cutoff)


System.out.println ("Safe condition");
else
System.out.println ("Hazadous condition");
} // End main
} // End class Pollution

44
1.4. Verification and Validation

q Errors may occur in any of the phases


of the program development process.
For example:

The specifications may not accurately


reflect information given in the
problem;
The algorithms may contain logical
errors;
The program may not be coded
correctly;
..

45
q The detection and correction of errors
is an important part of software
development and is known as validation
and verification.
Validation is concerned with checking
that the algorithms and the programs
meet the problems specification.
Verification refers to checking that
they are correct and complete.

q Errors may be detected at various


stages of program processing and may
cause the processing to be terminated.

46
q The three types of errors are Syntax
error or Compilation error, Run-Time
error and Logical error.

q If you have any statement which does


not conform to the syntactic rules of a
given language, the compiler will
produce a syntax error.

47
q Run-time errors occur during program
execution. They cause the program to
terminate abnormally. E.g, division by
zero will cause a run-time error.
q When you have a logical error, the
program compiles and executes
without complaint, but it produces
incorrect results. E.g. A + B is typed in
as A * B.

48
q Errors that are detected by the
computer system are relatively easy to
identify and correct, but not logical
errors.

q It is important that the user run a


program several times with input data
for which the correct results are known
in advance.

q A program cannot be considered to be


correct until it has been checked with
several sets of test data.

49
1.5. Software Engineering

q Programming and problem solving is


an art in that it requires a good deal of
imagination, ingenuity and creativity.

But it is also a science in that certain


techniques and methodologies are
commonly used.

q The term software engineering has


come to be applied to the study and use
of these techniques.
50
q The life cycle of software
engineering consists of five basic
phases:

1. Problem analysis and specification


2. Design
3. Coding
4. Verification and validation
5. Maintenance

51
Problem Analysis and Specification

q Most real-world problems are often


stated vaguely and imprecisely. In
these situations, many questions must
be answered to describe more
completely the problems input and
output in order to complete the
problems specification.

52
E.g. Computerize the payroll system.

Possible questions are:


What information is available for each
employee?
How is the program to access this
data?
Has this information been validated, or
must the program provide error
checking?
In what format should the output be
displayed?
Are paychecks being printed?
Must additional reports be generated
for company executes and/or
government agencies?
53
Other questions deal more directly with
the required processing:

Are employees paid on an hourly or


a salary basis, or are there some of
each?
What premium, if any, is paid for
overtime?
What items must be withheld for
CPF, loan repayment, and the like
and how are they to be computed?

54
Many other questions must be
answered before the specification of
the problem is complete and the design
of the algorithms and programs can
begin:

Will the users be technically


sophisticated, or will they be
novices so that the software must be
made extra user friendly and
robust?
How often will the software be
used?
Etc, Etc .

System analyst or programmers


55
responsibility?
Design

q A divide-and-conquer strategy is used,


in which the original problem is
partitioned into simpler subproblems,
each of which can be considered
independently.

q Use Structure Diagram to depict the


relationships between the subproblems.

56
q Top-down approach
The top-down approach to software
development allows the programmer to
design and test an algorithm and the
corresponding program module for
each subproblem independently of the
others.

57
Payroll System

Obtain
Obtain perform
Perform display
Display
input
input calculations
calculation result
results
data
data

First Level Structure Diagram

58
Second Level Structure Diagrams

Obtain
Input
data

Obtain permanent Obtain


employee current
information information

59
Perform
Calculation

Calculate Calculate Calculate net


Gross withholding Pay
pay

60
Display
Result

Print Print Summary


paychecks reports

61
Third Level Strucure Diagrams

Calculate
Gross Pay

Salaried Hourly

62
Program Coding

q Coding is the process of implementing


data structures and algorithms in some
programming language.

If the design plan has been developed


carefully and completely, this
translation process is nearly automatic.

63
q Integration is the process of combining
a number of subprograms into a
complete program or system of
programs.

Regardless of which language is used,


certain programming practices
contribute to the development of
correct, readable and understandable
programs.

64
One principle is that program should
be well structured. There are two
guidelines:
1. Use a top-down approach when
developing a program for a
complex problem.

2. Strive for simplicity and clarity.

65
A second principle is that each
program unit should be documented.
In particular
1. Each program unit should include
opening documentation.

2. Comments should also be used to


explain key program segments
and/or segments whose purpose or
design is not obvious.

3. Meaningful identifiers should be


used.
66
A third principle has to do with a
programs appearance. A program
should be formatted in a style that
enhances its readability. The
following are some guidelines for
program style:
1. Use spaces between the items in a
statement to make it more
readable.

2. Insert a blank line between


sections of program and whenever
appropriate in a sequence of
statements to set off blocks of
statements.
67
3. Adhere rigorously to alignment
and indentation guidelines to
emphasize the relationship
between various parts of the
program.

q It is often difficult for beginning


programmers to appreciate the
importance of learning good
programming habits that lead to the
design of readable and understandable
programs.
68
As hardware costs continue to decrease
and programmer costs increase, the
importance of reducing programming
and maintenance costs and the
corresponding importance of writing
programs that can be easily read and
understood by others continue to grow.

69
Program Execution and Testing

q Obviously the most important


characteristic of any program is that it
must be correct.

q Since errors may occur at each phase of


the development process, different
kinds of tests are required to detect
them:
Unit tests
Integration tests
System tests

These correspond to the various phases


of the software life cycle which is 70
knows as the V Life Cycle Model
Analysing problem Maintenance
formulating Specifications

Statement of Final
Specification System

Designing System
the system testing

System Integrated
plan modules

Designing and Integration


Coding modules testing

Program Units Tested program units

71
Unit testing
Maintenance

q Maintenance is a major component of


the life cycle of software. E.g.

Modify software to improve


performance
To add new feature
External factors

Poor structure high cost in


maintenance

72

You might also like