CSC102
CSC102
FACULTY OF COMPUTING
COURSE CONTENTS
1. Introduction
2. General Problem Solving Strategies
3. Concepts of Algorithm
4. Major Components of Algorithm
5. Properties of Algorithm
6. Role of Algorithm in Problem Solving
7. Ways of expressing Algorithm
8. Algorithm Development Methodologies
9. Top-Down Design
10. Object Oriented Design
11. Implementations strategies
12. Specify the problem requirements (Requirement Specification).
13. Analyze the problem (Analysis)
14. Design the algorithm to solve the problem (Design).
15. Implement the algorithm (Implementation).
16. Test and verify the completed program (Testing).
17. Maintain and update the program (Maintenance).
18. Applications of Software Development Methods in Problem Solving.
Introduction to problem solving
Based on the above definitions we can formally define problem solving as the act of finding a
solution to perplexing, distressing, vexing or unsettled question. Though the definition of
problems cited in the first paragraph suits this definition, some of them are not suitable in the
context of computing. This is because computers are limited in its problem solving Capabilities.
Computers cannot be used in solving problems involving physical activities or emotions.
A typical single CPU computer processes information as shown in Figure 1.1. Problems are
solved using a computer by obtaining some kind of user input (e.g., keyboard/mouse information
or game control movements), then processing the input and producing some kind of output (e.g.,
images, text, sound). Sometimes the incoming and outgoing data may be in the form of hard
drives or network devices.
In regards to problem solving, we will apply the above model in that we will assume that we are
given some kind of input information that we need to work with in order to produce some
desired output solution. However, the above model is quite simplified. For larger and more
complex problems, we need to iterate (i.e., repeat) the input/process/output stages multiple times
in sequence, producing intermediate results along the way that solve part of our problem, but not
necessarily the whole problem. For simple computations, the model below is sufficient.
Figure 1.1: Computer information processing model
Problems range from simple to complex. The complexity of a problem lies in the complexity in
finding a suitable solution. For example, the problem of having to come to class early is simpler
than that of gaining an admission. Thus, your solution to gaining an admission will require more
prudent strategies and implementations than that of coming early to class. In addition,
authenticating a bank transaction online will be more complex than authenticating a game login.
To ensure accurate, fast, safe and efficient solutions are gotten to problems, procedures must be
adhered to when finding solutions to problems. We will be discussing such procedures below:
3. Develop an Algorithm
6. Documentation.
1. Understand/Define the problem: A detailed understanding of the problem that states the
objectives of the given problem must be known to proffer a solution that solves the
problem.
2. Analyze the problem: Analysis of the problem entails a thorough breakdown of possible
solutions with the evaluation of these methods. Here, you may need to break down your
defined problems into modules and solve them as entities. Strategies and methods are
considered and evaluated. By the end of this phase, you should have a broad overview of
the sequence of operations to be implemented to solve your problem.
3. Develop an algorithm: Define a step by step set of instruction from the sequence of
operations gotten from your analysis. Just as you have a series of instructions to follow
through for a food recipe, your solution should be in form of an algorithm. An algorithm
is the step-by-step instruction used to solve a problem. Your algorithm can be revised
until it captures all the features of your analysis.
4. Implement the algorithm (Coding): Your algorithm which may be in natural language,
flowchart, or pseudocode will have to be converted into a high-level programming
language understood by the computer. Each step in your algorithm is converted to its
equivalent instruction(s) in the high-level language chosen for implementation.
Testing and De-bugging checks through the problem definition and analysis ensuring that every
needed requirement is met. This phase either takes you back to your problem definition phase
and down the chain, or takes you to program deployment. Some categories of testing are listed
below.
b. Unit testing: Individual unit of software, i.e. group of computer program, modules, usage
procedures and operating procedures are tested to determine whether they are suitable for
use or not. This is normally done by the programmer who writes the code.
c. Integration testing: It is done before, during and after integration of new module into the
main software package. One piece of software can contain several modules which are
created by different programmers. It is crucial to test each module effect on the entire
program modules.
d. System testing: This is done by the professional testing agent on the completed product
before it is introduced to the market (users).
e. Acceptance testing: Testing of the product done by the actual end users.
Acceptance testing
System testing
Integrated testing
Unit testing
6. Documentation: This is a phase usually neglected though very critical. Here, every
process involved in problem solving are meticulously documented. This helps in note
sharing, project handovers, maintenance, evaluation, upgrade as well as debugging. You
must be diligent to document through the process as information and decisions can be lost
with every passing phase.
WEEK 2
ALGORITHMS
In our daily activities, we perform tasks by carrying out some sequence of activities. For
example, getting to school every morning, wearing a tie, making breakfast are examples of tasks
that require a sequence of operations/activities. The following are examples of tasks that require
steps of procedures:
Step1
35: 1, 5, 7, and 35
Step2
The step-by-step sequence of tasks to solve the above problems can be referred to as algorithms.
An algorithm is a sequential set of instructions followed to proffer solutions to a problem.
Necessity of an Algorithm: Designing algorithms could be complex and tasking, why then are
algorithms a necessity? Algorithms increase the reliability, accuracy and efficiency of obtaining
solutions. Without an algorithm, problem solving processes will be disorderly, confusing, and
frustrating, with no provision to efficiently manage systems, debugging and upgrade will be
close to impossible, and such a system will barely be reliable. An algorithm that is dependable,
correct, efficient and has a good execution speed will always produce efficient solutions and will
provide for effective maintenance.
A problem can have more than one algorithm, what then are the metrics for choosing the
algorithm to implement?
- Reliability
- Accuracy
- Speed
- Cost
Note: There’ll sometimes be trade-offs between these factors to choose the algorithm that best
suit the solution to your problem as it relates to the resources available.
Characteristics of an algorithm:
1. Finiteness: An algorithm must terminate after a finite number of steps. Termination may
either mean an output was gotten or a message given.
3. Generality: It should be wholesome such that it can do similar tasks for any input of
data.
4. Effectiveness: Every step must be doable. Each step can be converted into a program
statement, and can be executed in a finite number of times.
5. Input/Output: The input precision (the kind, volume and format of data) should be
specified. The kind, volume and format of the output data should also be precise.
Algorithms should efficiently use resources (i.e. Fast speed and minimal RAM or disk space).
Note: The correctness of the output that a computer gives depends on the correctness of input
provided and the accuracy of the designed process.
WEEK 3
Design of a solution can only begin once the input, output and processing rules have been
clarified. This information is often represented in a chart format, like the Input-Processing-
Output (IPO) chart shown below. The IPO chart below is for calculating the average of two
numbers.
Input Processing Output
Number 1
Add Number 1 and Number 2 and divide by 2 Average of the two numbers
Number 2
Design involves developing an algorithm, which can often be a difficult process. As an aid to
design structured techniques may be used:
• Top down design - An approach where the overall high level view is determined. The
large problem is then divided into individual smaller problems which are solved
separately in their own module.
• The algorithm is initially functional (though limited in scope) and as more modules are
added, the overall solution becomes more and more functional.
STEPWISE REFINEMENT: This method of solving problems works "hand in hand" with
Top-Down Design. This method involves continual development and refinement of a broad
solution into more detailed mini solutions which are combined to solve the broad problem. This
continual process of refinement is called Stepwise Refinement.
STRUCTURED DESIGN: The use of the correct control structures is an important part of
programming. The main reason for their implementation regards "correctness" of an algorithm.
The "correctness" refers to whether or not an algorithm does what it is supposed to do. The
correct structures include Sequence, Selection and Repetition.
The process of Top-Down design may be enhanced through the use of structure charts. Using the
problem of finding the average of two numbers, the following structure chart may be used to
represent a breakdown of the problem.
The structure shown above would lead to an algorithm for the main program as shown below
Begin Mainprogram
Intitialise Variables
Calculate Average
Print Results
End Mainprogram
Each of these smaller problems could now be solved with the following algorithms :
Initialise
Get two numbers Calculate Average Print Results
Variables
Add 1 to count
End while
End
We now have a functional algorithm through top-down design and stepwise refinement. At a
later stage this algorithm could be coded into a programming language and made to run on a
computer.
REPRESENTATIONS OF ALGORITHM
There are three common formats of expressing algorithms. The three methods are: Natural
language, flowchart and pseudocode. In choosing any of the methods one must keep in mind the
following:
Flow of Control
The flow of control depicts the flow of events as represented in the flow chart. The events can
flow in a sequence, or on branch based on a decision or even repeat some part for a finite number
of times.
1. Sequence
If we look at the examples above, the statements are executed one after another, i.e., in a
sequence. Such algorithms where all the steps are executed one after the other are said to execute
in sequence. However, statements in an algorithm may not always execute in a sequence. We
may sometimes require the algorithm to either do some routine tasks in a repeated manner or
behave differently depending on the outcomes of previous steps.
2. Selection
Let’s consider a situation whereby your home is far away from your school. With reference to
that, let us answer the following questions
There may be multiple routes between home and school. We might take the shortest route in the
morning. But while coming back home in the traffic. Therefore, we could take another route with
less traffic. Hence, the above problem involves some decision making based on certain
conditions.
Conditions
True False
4. Repetition
When giving directions to go someplace, we say something like, “walk 50 steps then turn right”.
Or “Walk till the next crossing then take a right turn”. Consider some other examples like:
• Natural Language: Algorithms can be represented in our everyday language. Steps are
written in simple conventional language.
• Pseudocode: Pseudo means “not real”, so, pseudocode means “not real/unreal codes”.
Pseudocode is essentially English with some defined rules of structure and some
keywords that make it appear a bit like program code. Pseudocodes are non-executable
codes of detailed instructions written in non-formal language that can be translated into
real codes by a programmer. Pseudocodes can be understood by non-programmers and
programmers alike. It has the advantage of not being so labourious to produce as
flowcharts. Pseudocode has the disadvantage of not being as clear and easy to read as a
flowchart - especially for beginner programmers. They are non-ambiguous, simple and
usually written with Keywords. These keywords are usually written in capital letters,
some of which are:
INPUT
COMPUTE
INCREMENT
DECREMENT
IF/ELSE
WHILE
TRUE/FALSE
2. Start with the statement of a pseudo code which establishes the main goal or the aim.
3. Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
4. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it
in programming.
5. Check whether all the sections of a pseudo code are complete, finite and clear to understand
and comprehend.
6. Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple
to understand even for a layman or client, hence don’t incorporate too many technical terms.
Pseudocode Elements
• for start and finish BEGIN MAINPROGRAM, END MAINPROGRAM - this is often
abbreviated to BEGIN and END - especially in smaller programs
• INPUT: This is data retrieved from the user through typing or through an input device.
• READ / GET: This is input used when reading data from a data file.
• PRINT, DISPLAY, SHOW: This will show your output to a screen or the relevant output
device.
• Structural elements come in pairs, e.g. for every BEGIN there is an END, for
every IF there is an ENDIF, etc.
STATEMENTS IN PSUEDOCODE
A statement is defined as an instruction that directs the computer to perform a specific action. In
writing pseudocode, we will refer to singular instructions as statements.
When writing pseudocode, we assume that the order of execution of the statements is from top to
bottom. This changes when using control structures, functions and exception handling.
For example;
Write an algorithm to display the sum of two numbers entered by user, using both pseudocode
and flowchart.
INPUT num1
INPUT num2
PRINT Result
Start
Print Result
Stop
Example 2: Write an algorithm to calculate area and perimeter of a rectangle, using both
pseudocode and flowchart.
INPUT length
INPUT breadth
PRINT Area
PRINT Perim
Start
Print Area
Print Perim
Rules of writing pseudocode
When writing pseudocode, everyone often has their own style of presenting things out since it’s
read by humans and not by a computer; its rules are less rigorous than that of a programming
language. However, there are some simple rules that help make pseudocode more universally
understood.
1. Always capitalize the initial word. Have only one statement per line.
3. Always end multiline sections using any of the END keywords (ENDIF, ENDWHILE,
etc.).
5. Use the naming domain of the problem, not that of the implementation. E.g., “Append
the last name to the first name” instead of “name = first+ last.”
Following these rules help you generate readable pseudocode and be able to recognize a not
well-written one.
Conditionals in pseudocode.
If <condition> then
There are situations where we also need to take action when the condition is not fulfilled
otherwise
IF — ELSE IF — ELSE
THEN smile
ENDIF
Here is an if statement with an else section. Else allows for some statements to be executed if the
“if” condition is not met.
Smile
ELSE
frown
ENDIF
smile
frown
ELSE
ENDIF
For Example, Let us write an algorithm to check whether a number is odd or even.
INPUT number
ELSE
Example 2
Let us write a pseudocode and draw a flowchart where multiple conditions are checked to
categorize a person as either child (<13), teenager (>=13 but <20) or adult (>=20),based on age
specified:
• Input: Age
Pseudocode is as follows:
INPUT Age
PRINT "Child"
PRINT "Teenager"
ELSE
PRINT "Adult"
The flowchart representation of the algorithm in shown as;
Start
Enter Age
Age <13
Age < 20
“Teenager”
“Adult”
“Child”
Stop
Repetition in Pseudocode
For example;
Write pseudocode and draw a flowchart to accept 5 numbers and find their average.
Start
count = 0, sum = 0
Stop
Input num
count = count + 1
In the example above, a counter called “count” keeps track of number of times the loop has been
repeated. After every iteration of the loop, the value of count is incremented by 1 until it
performs the set number of repetitions, given in the iteration condition.
There are situations when we are not aware beforehand about the number of times a set of
statements need to be repeated. Such requirements of unknown number of repetitions are handled
using WHILE construct
For example; Write pseudocode and draw flowchart to accept numbers till the user enters 0 and
then find their average.
Pseudocode is as follows:
The flowchart to accept numbers till the user enters 0 representation is shown as thus;
Start
count = 0, sum = 0
Input num
num = = 0?
average = sum / count Print average
Stop
count = count + 1
Input num
In this example, we do not know how many numbers a user is going to enter before entering 0.
This is handled by checking the condition repeatedly till the condition becomes false.
Example:
Prepare an algorithm that prints name and weekly wages for each employee out of 10 using
pseudo code.
Solution
BEGIN
STORE 0 TO Sum
STORE 1 TO Count
INCREMENT Count by 1
END WHILE
END
1. Better readability. Often, programmers work alongside people from other domains, such
as mathematicians, business partners, managers, and so on. Using pseudocode to explain
the mechanics of the code will make the communication between the different
backgrounds easier and more efficient.
2. Ease up code construction. When the programmer goes through the process of
developing and generating pseudocode, the process of converting that into real code
written in any programming language will become much easier and faster as well.
3. A good middle point between flowchart and code. Moving directly from the idea to
the flowchart to the code is not always a smooth ride. That’s where pseudocode presents
a way to make the transition between the different stages somewhat smoother.
Advantages of Pseudocode
Preparing pseudocode while solving any problem through computer has following advantages:
1. It allows the designer to focus on main logic without being distracted by programming
languages syntax.
5. Unlike algorithms, pseudocodes are concise so pseudocodes are more readable and easier
to modify.
Disdvantages of Pseudocode
1. There are no accepted standards for writing pseudocodes and designer use their own style
while writing pseudocodes.
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown
as long as it does not exceed 3 symbols.
• From the bottom of the page to the top of the same page.
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
Example 1
Before developing the algorithm, let us first identify the input, process and output:
Start
Example 2
Write an algorithm to read values for three variables. U, V and W and find a value for result
from the formula. Result= U+V2/W
START
Solution
Example 3
STOP
Write an algorithm to find the square of a number.
The algorithm to find square of a number can be represented pictorially using flowchart as
shown below:
Example 4
Suppose you are given 20 numbers. Prepare the algorithm that’s add these numbers and find the
average. Draw the flowchart
Solution
Algorithm
Step 1. Set up a counter (I) which counts the number of times the loop is executed. Initialize
counter (I) to 1.
Step 5. Check how many times you have added up the number, if it is not up to the required
number of times, go to step (iii)
Step 7. Stop
Start
I I, sum 0
Sum sum+1
I I+1
Is I <=20
Average=sum/20
Print average
Stop
Example 5
Start
Is the bulb
switched Switch on
on?
Bulb
on
Call
Is it
electrician
burnt
Stop
Example: 6
Where p is principle amount, N is the number of years and R is the rate of interest.
Step 4: stop
start
Read P ,N ,R
P*N*R/100
Stop