0% found this document useful (0 votes)
80 views43 pages

CSC 102 Lecture Note

Problem solving and algorithm

Uploaded by

ladyanuelle206
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views43 pages

CSC 102 Lecture Note

Problem solving and algorithm

Uploaded by

ladyanuelle206
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Federal University Dutse

Faculty Of Science
Department Of Computer Science

CSC 102: Introduction To Problem Solving (3 Units)


Lecture Note

1
Chapter One (1) General Introduction
1.1 What is a Formal Problem?
Usually the term problem is used to refer to a situation where it is not
immediately obvious how to reach the goal. The exact same situation
can be a problem for one person and not a problem (perhaps just a
simple activity or routine exercise) for another person. Problem solving
consists of moving from a given initial situation to a desired goal
situation. That is, problem solving is the process of designing and
carrying out a set of steps to reach a goal.
To solve the problem, you need to travel from a starting point, called the
initial state, to an end point, called the goal state. The initial state
includes all of the knowledge and resources you currently have
available. The goal state refers to the solution that you want to reach.
The set of possible ways to travel from the initial state to the goal state is
called the problem space.

Figure1. Problem-solving process--how to achieve final goal?


Problem-solving is a tool, a skill, and a process. As a tool is helps you
solve a problem or achieve a goal. As a skill you can use it repeatedly
throughout your life. And, as a process it involves a number of steps.
Problem-solving is a mental process that involves discovering, analyzing
and solving problems. The ultimate goal of problem-solving is to
2
overcome obstacles and find a solution that best resolves the issue.
The best strategy for solving a problem depends largely on the unique
situation. In some cases, people are better off learning everything they
can about the issue and then using factual knowledge to come up with a
solution. In other instances, creativity and insight are the best options.
1.2 Problem Solving in Everyday Life
People make decisions every day to solve problems that affect their
lives. The problems may be as unimportant as what to watch on
television or as important as choosing a new profession. If a bad
decision is made, time and resources are wasted, so it’s important that
people know how to make decisions well. There are six steps to follow
to ensure the best decision in making problem solving as a process.
These six steps in problem solving include the following:
1.2.1 Identify the problem. The first step toward solving a problem is
to identify the problem. In a classroom situation, most problems have
been identified for you and given to you in the form of written
assignments or problems out of a book. However, when you are doing
problem solving outside the classroom, you need to make sure you
identify the problem before you start solving it. If you don’t know what
the problem is, you cannot solve it.
1.2.2 Understand the problem. You must understand what is involved
in the problem before you can continue toward the solution. This
includes understanding the knowledge base of the person or machine for
whom you are solving the problem. If you are setting up a solution for a

3
person, then you must know what that person knows. A different set of
instructions might have to be used depending on this knowledge base.
1.2.3 Identify alternative ways to solve the problem. This list should
be as complete as possible. You might want to talk to other people to
find other solutions than those you have identified. Alternative solutions
must be acceptable ones. You could go from Dutse to Jos by way of
Kano, but this would probably not be an acceptable solution to your
travel needs.
1.2.4 Select the best way to solve the problem from the list of
alternative solutions. In this step, you need to identify and evaluate the
pros and cons of each possible solution before selecting the best one. In
order to do this, you need to select criteria for the evaluation. These
criteria will serve as the guidelines for evaluating each solution.
1.2.5 List instructions that enable you to solve the problem using the
selected solution. These numbered, step-by-step instructions must fall
within the knowledge base set up in step 2. No instruction can be used
unless the individual or the machine can understand it. This can be very
limiting, especially when working with computers.
1.2.6 Evaluate the solution. To evaluate or test a solution means to
check its result to see if it is correct, and to see if it satisfies the needs of
the person(s) with the problem. (When a person needs a piece of
furniture to sleep on, buying her a cot may be a correct solution, but it
may not be very satisfactory.) If the result is either incorrect or

4
unsatisfactory, then the problem solver must review the list of
instructions to see that they are correct or start the process all over again.
If any of these six steps are not completed well, the results may be less
than desired. People solve problems daily at home, or work, or wherever
they go. Problems at home include such things as what to cook for
dinner, which movie to see this evening, which car to buy, or how to sell
the house. At work, the problems might involve dealing with fellow
employees, work policies, management, or customers. The better the
decisions an employee can make, the more valuable that person will be
to the company. In each case, the six steps in problem solving can be
followed. Most people use them without even knowing it.

1.3 The 4 steps in using a Computer as a Problem Solving Tool


- Develop an Algorithm and a Flowchart.
- Write the program in a computer language. (i.e. Java or C++, Enter
the program into the computer.
- Test and debug the program.
- Run the program, input data, and get the results from the computer.

1.4 Types of Problems


Broadly speaking, two(2) major types of problems have been
recognized: Algorithmic or Heuristic in nature.
1.4.1 Algorithmic
Problems do not always have straight forward solutions. Some problems,
such as balancing a checkbook or baking a cake, can be solved with a
5
series of actions. These solutions are called algorithmic solutions. Once
the alternatives have been eliminated, for example, and once one has
chosen the best among several methods of balancing the checkbook, the
solution can be reached by completing the actions in steps. These steps
are called the algorithm.
1.4.2 Heuristic
The solutions of other problems, such as how to buy the best stock or
whether to expand the company, are not so straightforward. These
solutions require reasoning built on knowledge and experience.
Solutions that cannot be reached through a direct set of steps are called
heuristic solutions.
The problem solver can use the six steps for both algorithmic and
heuristic solutions. However, in step 6, evaluating the solution, the
correctness and appropriateness of heuristic solutions are far less certain.
It’s easy to tell if your completed checkbook balance is correct and
satisfactory, but it’s hard to tell if you have bought the best stock.
With heuristic solutions, the problem solver will often need to follow the
six steps more than once, carefully evaluating each possible solution
before deciding which is best.

1.5 Problems and Obstacles in Problem-Solving


Of course, problem-solving is not a perfect process. There are a number
of different obstacles that can interfere with our ability to solve a
problem quickly and efficiently. Researchers have described a number

6
of these mental obstacles, which include functional fixedness, irrelevant
information and assumptions.
1.5.1 Functional Fixedness: This term refers to the tendency to view
problems only in their customary manner. Functional fixedness prevents
people from fully seeing all of the different options that might be
available to find a solution.
1.5.2 Irrelevant or Misleading Information: When you are trying to
solve a problem, it is important to distinguish between information that
is relevant to the issue and irrelevant data that can lead to faulty
solutions. When a problem is very complex, the easier it becomes to
focus on misleading or irrelevant information.
1.5.3 Assumptions: When dealing with a problem, people often make
assumptions about the constraints and obstacles that prevent certain
solutions.
1.5.4 Mental Set: Another common problem-solving obstacle is known
as a mental set, which is the tendency people have to only use solutions
that have worked in the past rather than looking for alternative ideas. A
mental set can often work as a heuristic, making it a useful problem-
solving tool. However, mental sets can also lead to inflexibility, making
it more difficult to find effective solutions.

1.6 PROBLEM
Name three current problems in your life that could be solved through an
algorithmic process. Explain why each of these problems is algorithmic
in nature.
7
Complete the six problem-solving steps to solve one of the problems you
listed in
question 1. Follow the form outlined as follows:
Step 1: Identify the problem.
Step 2: Understand the problem.
a. Comments about the problem to aid in understanding it.
b. Description of the knowledge base (this list would include what you
would be expected to know to follow the solution).
Step 3: Identify alternative solutions.
Solution Pros Cons
a.
b.
c.
.
.
.
Step 4: Select the best solution.
Why did you select this solution?
Step 5: List a set of numbered step-by-step instructions to attain the
solution.
1.
2.
3.
.
.
Step 6: Test the solution.
Does this solution work? If not, how might you change the solution so it
will work
8
Chapter Two (2) Problem-Solving Strategies

2.1 Problem-Solving Strategies


A strategy can be thought of as a plan, a heuristic, a rule of thumb, a
possible way to approach the solving of some type of problem. For
example, perhaps one of the problems that you have to deal with is
finding a parking place at work or at school. If so, probably you have
developed a strategy--for example, a particular time of day when you
look for a parking place or a particular search pattern. Your strategy may
not always be successful, but you find it useful.
Every problem-solving domain has its own strategies. Below are some
of the strategies used in problem solving
2.1.1Algorithms: Problems do not always have straight forward
solutions. Some problems, such as balancing a checkbook or baking a
cake, can be solved with a series of actions. These solutions are called
algorithmic solutions. Once the alternatives have been eliminated, for
example, and once one has chosen the best among several methods of
balancing the checkbook, the solution can be reached by completing the
actions in steps. These steps are called the algorithm.
While an algorithm guarantees an accurate answer, it is not always the
best approach to problem solving. This strategy is not practical for many
situations because it can be so time-consuming. For example, if you
were trying to figure out all of the possible number combinations to a
lock using an algorithm, it would take a very long time.

9
2.1.2 Heuristics: The solution to some problems, such as how to buy the
best stock or whether to expand the company, are not so straightforward.
These solutions require reasoning built on knowledge and experience.
Solutions that cannot be reached through a direct set of steps are called
heuristic solutions.
Heuristic is a Greek word that means ‘find’. In computing, this refers to
experience-based techniques for problem solving, learning and
discovery that give a solution which is not guaranteed to be optimal.
Heuristic methods are used to speed up the process of finding a
satisfactory solution via mental shortcuts to ease the cognitive load of
making a decision. Examples of this method include: rule of thumb (a
rough and practical approach, based on experience, rather than a
scientific), educated guess, an intuitive judgment, or common sense.
Unlike algorithms, heuristics do not always guarantee a correct solution.
However, using this problem-solving strategy does allow people to
simplify complex problems and reduce the total number of possible
solutions to a more manageable set.
2.1.3 Trial-and-Error:A trial-and-error approach to problem-solving
involves trying a number of different solutions and ruling out those that
do not work. This approach can be a good option if you have a very
limited number of options available. If there are many different choices,
you are better off narrowing down the possible options using another
problem-solving technique before attempting trial-and-error.

10
2.1.4 Insight: In some cases, the solution to a problem can appear as a
sudden insight. According to researchers, insight can occur because you
realize that the problem is actually similar to something that you have
dealt with in the past, but in most cases the underlying mental processes
that lead to insight happen outside of awareness

2.2 Problems, Solutions, and Tools

I have a problem! I need to thank Aunt Kay for the birthday present she
sent me. I could send a thank you note through the mail. I could call her
on the telephone. I could send her an email message. I could drive to her
house and thank her in person. In fact, there are many ways I could
thank her, but that's not the point. The point is that I must decide how I
want to solve the problem, and use the appropriate tool to implement
(carry out) my plan. The postal service, the telephone, the internet, and
my automobile are tools that I can use, but none of these actually solves
my problem. In a similar way, a computer does not solve problems, it's
just a tool that I can use to implement my plan for solving the problem.
Knowing that Aunt Kay appreciates creative and unusual things, I have
decided to hire a singing messenger to deliver my thanks. In this context,
the messenger is a tool, but one that needs instructions from me. I have
to tell the messenger where Aunt Kay lives, what time I would like the
message to be delivered, and what lyrics I want sung. A computer
program is similar to my instructions to the messenger.

11
The story of Aunt Kay uses a familiar context to set the stage for a
useful point of view concerning computers and computer programs. The
following list summarizes the key aspects of this point of view.
 A computer is a tool that can be used to implement a plan for
solving a problem.
 A computer program is a set of instructions for a computer. These
instructions describe the steps that the computer must follow to
implement a plan.
 An algorithm is a plan for solving a problem.
 A person must design an algorithm.
 A person must translate an algorithm into a computer program.
This point of view sets the stage for a process that we will use to develop
solutions to Jeroo problems. The basic process is important because it
can be used to solve a wide variety of problems, including ones where
the solution will be written in some other programming language.

12
Chapter Three (3) Concepts and Properties of Algorithm

3.1 Origin of the word “Algorithm”


The word algorithm comes from the name of the 9th century Persian
Muslim mathematician Abu Abdullah Muhammad ibn Musa Al-
Khwarizmi. The word algorism originally referred only to the rules of
performing arithmetic using Hindu-Arabic numerals but evolved via
European Latin translation of Al-Khwarizmi's name into algorithm by
the 18th century. The use of the word evolved to include all definite
procedures for solving problems or performing tasks.

3.2 Definition of an Algorithms:


An algorithm is an ordered set of unambiguous, executable steps that
defines a terminating process. An algorithm is a step-by-step procedure
that will always produce a correct solution. A mathematical formula is a
good example of a problem-solving algorithm. While an algorithm
guarantees an accurate answer, it is not always the best approach to
problem solving. This strategy is not practical for many situations
because it can be so time-consuming. For example, if you were trying to
figure out all of the possible number combinations to a lock using an
algorithm, it would take a very long time.
A representation of an algorithm is called a program. For the
convenience of humans, computer programs are usually printed on paper
or displayed on computer screens. For the convenience of machines,
programs are encoded in a manner compatible with the technology of the
machine. The process of developing a program, encoding it in machine-
13
compatible form, and inserting it into a machine is called
programming. Programs, and the algorithms they represent, are
collectively referred to as software, in contrast to the machinery itself,
which is known as hardware.

3.3 Properties of Algorithm:-


 It is written in simple English.
 Each step of an algorithm is unique and should be self
explanatory.
 An algorithm must have at least one input.
 An algorithm must have at least one output.
 An algorithm has finite number of steps.
 It should provide the correct solutions
 Should have an end point

3.4 Benefits Of Using Algorithm In Problem-Solving


A problem can be solved by using a computer only if an algorithm can
be written for it. In addition, the use of algorithm provides many other
benefits:-
• While writing an algorithm, you identify the step-by-step procedure,
the major decision points, and the variables necessary to solve the
problem. This helps you in the development of the corresponding
program.
• Identification of the procedure and the decision points reduces the
problem into a series of smaller problems of more manageable size.

14
Therefore, problems that would be difficult or impossible to solve as a
whole can be approached as a series of small solvable sub problems.
• With the use of an algorithm, decision making becomes a more rational
process. This is because algorithms comprise of sub tasks, where each
sub task is atomic in nature and is supported by facts.
• With the use of an algorithm, the same specified steps are used for
performing the tasks. This makes the process more consistent and
reliable.
3.5 Development Processes of An Algorithm

There are many ways to write an algorithm. Some are very informal,
some are quite formal and mathematical in nature, and some are quite
graphical. The instructions for connecting a DVD player to a television
are an algorithm. A mathematical formula such as πR2 is a special case
of an algorithm. The form is not particularly important as long as it
provides a good way to describe and check the logic of the plan.
The development of an algorithm (a plan) is a key step in solving a
problem. Once we have an algorithm, we can translate it into a computer
program in some programming language. Our algorithm development
process consists of five major steps.
Step 1: Obtain a description of the problem.
Step 2: Analyze the problem.
Step 3: Develop a high-level algorithm.
Step 4: Refine the algorithm by adding more detail.
Step 5: Review the algorithm.

15
Step 1: Obtain a Description of the Problem.

This step is much more difficult than it appears. In the following


discussion, the word client refers to someone who wants to find a
solution to a problem, and the word developer refers to someone who
finds a way to solve the problem. The developer must create an
algorithm that will solve the client's problem.
The client is responsible for creating a description of the problem, but
this is often the weakest part of the process. It's quite common for a
problem description to suffer from one or more of the following types of
defects: (1) the description relies on unstated assumptions, (2) the
description is ambiguous, (3) the description is incomplete, or (4) the
description has internal contradictions. These defects are seldom
(occasionally) due to carelessness by the client. Instead, they are due to
the fact that natural languages (English, French, Korean, etc.) are rather
imprecise(inaccurate). Part of the developer's responsibility is to identify
defects in the description of a problem, and to work with the client to
remedy those defects.

Step 2: Analyze the problem.

The purpose of this step is to determine both the starting and ending
points for solving the problem. This process is analogous (similar) to a
mathematician determining what is given and what must be proven. A
good problem description makes it easier to perform this step.

16
When determining the starting point, we should start by seeking answers
to the following questions:
 What data are available?
 Where is that data?
 What formulas pertain to the problem?
 What rules exist for working with the data?
 What relationships exist among the data values?
When determining the ending point, we need to describe the
characteristics of a solution. In other words, how will we know when
we're done? Asking the following questions often helps to determine the
ending point.
 What new facts will we have?
 What items will have changed?
 What changes will have been made to those items?
 What things will no longer exist?

A good way to analyze a problem is to separate it into four parts:


a. The given data
b. The required results
c. The processing that is required in the problem
d. A list of solution alternatives
This is well represented in the Problem Analysis Chart.

17
Problem Analysis Chart (PAC)
Programmer can use this form/chart to sort problem out,
 PAC allows the problem solver to eliminate the words and glean
only the facts from the problem.
 Data, constants and variables, go in to the Given Data section.
 Requirements for the output reports would be entered under
Required Results.
 Any equations or other processing requirements would be listed in
the Processing Required section.
 Finally, the programmer would write any other ideas that spring to
mind concerning the solution in the Solution Alternatives section.
We see example HERE...
 Consider a problem to Calculate the gross pay of an employee
given the hours worked and the rate of pay.
We know that the gross pay is calculated by multiplying the hours
worked by the rate of pay.
i.e, GrossPay = Hours * PayRate

18
Thus, using the PAC, we’ve:

Problem Analysis Chart for the Payroll Problem

1. Define the hours worked and the pay rate as constants.


2. Define the hours worked and the pay rate as input values

The second alternative will be used, as signified by the asterisk in the


figure, since the program will not need to be changed in order to
calculate the gross pay for another employee.

The problem analysis chart is an aid to clear thinking because it


helps the problem solver to identify the essential data and information in
a problem and to disregard the nonessentials. Most problems
programmers work with are word problems. This is true whether they
are working in a classroom situation or out on the job. The PAC helps to
pare down the words.

Problem: Mary Smith is looking for the bank that will give the most
return on her money over the next five years. She has $2,000 to put into
a savings account. The standard equation to calculate principal plus
interest at the end of a period of time is

19
Amount = P *( 1 + I/M)^(N * M)
where:
P = Principal (amount of money to invest, in this case $2,000)
I =Interest (percentage rate the bank pays to the investor)
N = Number of Years (time for which the principal is invested)
M =Compound Interval (the number of times per year the interest is
calculated and added to the principal)
 PAC aids to clear thinking because it helps the problem solver
identify the essential data and information in a problem and to
disregard the nonessentials.
 Most problems that programmers work with are word problems.
This is true whether they are working in a classroom situation or
out on the job.

Step 3: Develop a high-level algorithm.


An algorithm is a plan for solving a problem, but plans come in
several levels of detail. It's usually better to start with a high-level
algorithm that includes the major part of a solution, but leaves the
details until later. We can use an everyday example to demonstrate a
high-level algorithm.
Problem: I need to send a birthday card to my brother, Mark.

Analysis' don't have a card. I prefer to buy a card rather than make one
myself.

20
High-level algorithm:
Go to a store that sells greeting cards
Select a card
Purchase a card
Mail the card
This algorithm is satisfactory for daily use, but it lacks details that would
have to be added were a computer to carry out the solution. These details
include answers to questions such as the following.
 "Which store will I visit?"
 "How will I get there: walk, drive, ride my bicycle, take the bus?"
 "What kind of card does Mark like: humorous(funny), sentimental
(emotional), risqué(naughty)?"
These kinds of details are considered in the next step of our process.
Step 4: Refine the algorithm by adding more detail.
A high-level algorithm shows the major steps that need to be followed to
solve a problem. Now we need to add details to these steps, but how
much detail should we add? Unfortunately, the answer to this question
depends on the situation. We have to consider who (or what) is going to
implement the algorithm and how much that person (or thing) already
knows how to do. If someone is going to purchase Mark's birthday card
on my behalf, my instructions have to be adapted to whether or not that
person is familiar with the stores in the community and how well the
purchaser known my brother's taste in greeting cards.
When our goal is to develop algorithms that will lead to computer
programs, we need to consider the capabilities of the computer and
provide enough detail so that someone else could use our algorithm to
21
write a computer program that follows the steps in our algorithm. As
with the birthday card problem, we need to adjust the level of detail to
match the ability of the programmer. When in doubt, or when you are
learning, it is better to have too much detail than to have too little.
Most of our examples will move from a high-level to a detailed
algorithm in a single step, but this is not always reasonable. For larger,
more complex problems, it is common to go through this process several
times, developing intermediate level algorithms as we go. Each time, we
add more detail to the previous algorithm, stopping when we see no
benefit to further refinement. This technique of gradually working from
a high-level to a detailed algorithm is often called stepwise refinement.
Stepwise refinement is a process for developing a detailed algorithm by
gradually adding detail to a high-level algorithm.

Step 5: Review the algorithm.

The final step is to review the algorithm. What are we looking for? First,
we need to work through the algorithm step by step to determine
whether or not it will solve the original problem. Once we are satisfied
that the algorithm does provide a solution to the problem, we start to
look for other things. The following questions are typical of ones that
should be asked whenever we review an algorithm. Asking these
questions and seeking their answers is a good way to develop skills that
can be applied to the next problem.

22
 Does this algorithm solve a very specific problem or does it solve
a more general problem? If it solves a very specific problem, should
it be generalized?
For example, an algorithm that computes the area of a circle having
radius 5.2 meters (formula π*5.22) solves a very specific problem, but
an algorithm that computes the area of any circle (formula π*R 2)
solves a more general problem.
 Can this algorithm be simplified?
One formula for computing the perimeter of a rectangle is:

length + width + length + width

A simpler formula would be:

2.0 * (length + width)

 Is this solution similar to the solution to another problem? How


are they alike? How are they different?
For example, consider the following two formulae:

Rectangle area = length * width


Triangle area = 0.5 * base * height

Similarities: Each computes an area. Each multiplies two


measurements.
Differences: Different measurements are used. The triangle formula
contains 0.5.
Hypothesis: Perhaps every area formula involves multiplying two
measurements.

23
Examples 1: Write an algorithm to determine a student’s final grade and
indicate whether it is passing or failing. The final grade is calculated as
the average of four marks.
Solution 1:
 Detailed Algorithm
 Step 1: Input M1,M2,M3,M4
 Step 2: GRADE  (M1+M2+M3+M4)/4
 Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
Endif

Example 2: Write an algorithm and draw a flowchart to convert the


length in feet to centimeter.

Solution 2:

 Detailed Algorithm
 Step 1: Input Lft
 Step 2: Lcm  Lft x 30
 Step 3: Print Lcm

Example 3: Write an algorithm and draw a flowchart to calculate the area of a


rectangle.

Solution 3:

 Detailed Algorithm
 Step 1: Input W,L
 Step 2: AL x W
 Step 3: Print A

24
Example4
Write an algorithm to calculate the simple interest using the formula.
Simple interest = P*T* R/100.
Where P is principle Amount, T is the number of years and R is the
rate of interest.
Solution 4:
Step 1: Read the three input quantities’ P, T and R.
Step 2 : Calculate simple interest as
Simple interest = P* T* R/100
Step 3: Print simple interest.
Step 4: Stop.

Example 5:
Write an algorithm to find the area of the triangle. Let b, c be the
sides of the triangle ABC and A the included angle between the given
sides.

Solution 5
Step 1: Input the given elements of the triangle namely sides b, c and
angle between the sides A.
Step 2: Area = (1/2) *b*C* sin A
Step 3: Output the Area
Step 4: Stop.

25
Chapter Four (4): Implementations Strategies,

4.1 Implementations Strategies


Steps of problem solving using an Algorithm

- Formulate a general idea


- Refine it into detailed step by step methods (perhaps using
pseudocode or flowchart).
NOTE; an algorithm is just a method that you can describe using a
pseudocode, flowchart, a program or any other way intelligible to man.

4.2 Pseudocode
Pseudocode is an artificial and informal language that helps
programmers to develop algorithms. Pseudocode is very similar to
everyday English.
 It is the Natural Language representation of a Program or
algorithm
 It uses the structural conventions of a programming language, but
is intended for human reading rather than machine reading
 It is used to explain a program to someone who may not
understand the particular programming language in which it was
made
 Pseudocode generally does not actually obey the syntax rules of
any particular language, there is no systematic standard form,
although any particular writer will generally borrow style and

26
syntax. Popular syntax sources include Pascal, BASIC, C, C++,
Java, and ALGOL
A few rules governing pseudocode are:
- Variable declarations mostly omitted.
- Function calls and blocks of code, such as code contained
within a loop, are often replaced by a one-line natural language
sentence.
- Show key words in capital letters eg. IF, ENDIF, DO, ENDDO,
THEN etc.
- Punctuation is optional
- Every IF must end with an ENDIF.
4.2.1 Advantages of using pseudocode
 It bridges the gap between human and computer languages
 It is an immediate notation that allows expression of program
logic in straight forward, easy to understand manner without
concerning the programmer with syntax details.
 It is easier to make changes to pseudocode than to a source
program in a high level language.
 It allows for structured walk-through
Examples 1: Write a pseudocode to determine a student’s final grade
and indicate whether it is passing or failing. The final grade is calculated
as the average of four marks

Pseudocode
 Input a set of 4 marks
 Calculate their average by summing and dividing by 4

 if average is below 50
27
Print “FAIL”
else
Print “PASS”
Example 2: Write a pseudocode to convert the length in feet to
centimeter.

Solution 2:
Pseudocode
 Input the length in feet (Lft)
 Calculate the length in cm (Lcm) by multiplying LFT
with 30
 Print length in cm (LCM)

Example 3: Write a pseudocode to calculate the area of a rectangle.

Solution 3:
Pseudocode
 Input the width (W) and Length (L) of a rectangle
 Calculate the area (A) by multiplying L with W
 Print A

4.3 Program Flow Chart


Program Flow Chart is a graphical representation of the program logic
in solving a problem. It uses the standard symbols in designing the input,
process and output of a program. Program flowcharts show the sequence
of instructions in a single program or subroutine. Different symbols are
used to draw each type of flowchart. Steps are described in boxes of
various kinds, and their order indicated by connecting them with arrows.
Flowcharts are used in analyzing, designing, documenting or managing a
process or program.
4.3.1 Symbols used in Program Flow Chart
The table below shows the symbols used in drawing the Program Flow

28
Chart.

4.3.2 Three Program Constructs in Program Flow Chart


All program designs can be constructed using three basic constructs. It is
also the concept of structured programming that a program should be
developed using the three basic constructs. The three basic constructs in
programming are:
 sequence
 selection
 iteration

29
When designing the program, we are also able to represent the three
basic constructs using the Program Flow Chart.
4.3.2.1Sequence
In a sequence construct, each instruction is executed in a serial manner,
one after another. For example, a program requires the user to enter two
numbers num1and num2. The program then calculates the answer by
dividing num1by num2, and displays the result before it terminates. The
diagram below shows the design of the program using the flowchart.

4.3.2.2 Selection
The selection construct provides a decision point that allows one of the
two choices to be chosen based on some value within a program. For
example, a program requires the user to enter two numbers num1and
num2. If the second number entered is zero, the program will display a
message “division by zero error”, otherwise it will calculate the answer
by dividing num1 by num2. The program then displays the result before

30
it terminates. The diagram below is a flowchart representation of the
design of the program.

Another example, if a program is a menu driven program, it allows the


user to make a choice. If the user selects the first option, it displays a
message “option one selected”. If option two is selected, it displays a
message “option two selected” and if user selects option three, it
displays a message “option three selected”. Lastly, if the user entered a
wrong option, a message “invalid option” will be displayed. The
diagram below shows the design of this program using the flowchart.

31
4.3.2.3 Iteration
The iteration construct allows a set of instructions to be repeated a
number of times based on the condition stated. The loop will end when
the condition has been fulfilled. For example, a program initializes the
value of variable ‘total’ to zero. It then requires the user to enter a
number. If the number that was entered is less than 1000, it will add the
number to the total and ask for another number to be entered. Only when
the user enters a number greater than 1000, the program will then

32
display the total that is accumulated before the program terminates. The
diagram below illustrates the design of the program using the flowchart.

Programming Exercises
1. Name any 4 symbols used in flowchart.
2. Use the flowchart to show the three program construct: sequence,
selection and iteration.
3. Connectors are sometimes in drawing a flowchart. Explain when
should a connector be used.

33
Program flowchart for Examples1 above

Program flowchart for Example 2 above

34
Program flowchart for Example 3 above

4.4 Program Flow Control

4.4.1 Selection Statements


In the previous chapter, we have learned how to write programs that can
accept inputs, we can therefore, alter the events that occur within the
program based on the user’s input allowing decision making to take
place. To make a decision, it involves choosing between two alternative
courses of action based some value within a program.

35
Selection statement allows our program to choose different paths of
execution based on the outcome of an expression or the state of the
variable. The expression or value upon which a decision is made is
always a Boolean value, which is always one of two values – true or
false. Java supports two kinds of selection statements: if or if..else
statement and the switch statement.
4.4.1.1 The if structure
A single if statement is sometimes called a single-alternate if because we
only perform an action based on one alternative.

syntax:
if (condition)
statement ; // executed when condition is true
Example
if (answer == ‘C’)
System.out.println(“You choose to continue.”);
If (answer == ‘Q’)
System.out.println(“You choose to quit.”);
4.4.1.2 The if..else structure
The if..else statement is called a dual-alternate if, which requires two
options for the next course of action. It provides the mechanism to
perform one action when a Boolean expression evaluates as true and
performs another action when the Boolean expression evaluates as false.
syntax:

36
if (condition)
statement 1; // executed when condition is true
else
statement 2; // executed when condition is false
Example
if (age >= 21)
System.out.println(“You are an adult”);
else
System.out.println(“You are a teenage”);

4.4.1.3 Nest if and Nested if..else Structure


We can code as many dependent statements as we need within an if or
an else statement. Such statements with an if inside another if are
commonly called nested if statements. Nested if statements are
particularly useful when two conditions must be met before some action
is taken.
syntax: nested if structure
if (condition 1)
if (condition 2)
statement;
Example
if ( itemSold > 3 )
if ( total > 1000 )
bonus = 50;

37
syntax: nested if..else structure
if (condition 1)
if (condition 2)
statement 1;
else
statement 2;
Example
if ( itemSold > 3 )
if ( total > 1000 )
bonus = 50;
else
bonus = 0;

4.4.2 Iteration Statements


To make the program more powerful, a loop structure can be included in
a program. It is a structure that allows a block of statements to be
executed repeatedly. A boolean expression will be evaluated within the
looping structure. If the expression is true, the block of statements called
the loop body will be executed and then the boolean expression is
evaluated again. The loop body will continue to execute as long as the
expression is true. It will end when the boolean expression is false. Java
supports three kinds of iteration statements: while, do..while and for
loop.

38
Chapter Five (5) Algorithm Design
Algorithm Design: is all about planning the solution
5.1 Organising the Solution:
Certain organizational tools will help you learn to solve problems on the
computer. The tools used in this module and illustrated in chapter 3 is
the problem analysis chart (PAC), which shows a beginning analysis
of the problem. other analysis tools include the structure chart or
interactivity chart, which shows the overall layout or structure of the
solution; the IPO chart, which shows the input, the processing, and the
output; the algorithms, which show the sequence of instructions
comprising the solution; and the flowcharts, which are graphic
representations of the algorithms and pseudocode, which represents a
language like solution. The coupling diagram shows the relationship
between the modules and the data needed for the modules. The Data
Dictionary lists all date variable names and their definitions. UML
(Unified Modeling Language) is a basic tool when using Object
Oriented Programming structure. To analyze a problem and set up the
most efficient solution, a programmer organizes the solution by using all
or some of these tools. When the programmer does not use these tools
during the problem-solving process, the solution takes longer to
program, and the final program is less efficient, lacks readability, and
increases programmer frustration.

5.2 Documenting a Solution


After applying this Problem solving tool you can now document the
solution, the solution documentation can be internal or external
documentation.
5.2.1 INTERNAL DOCUMENTATION consists of remarks written
with the instructions to explain what is being done in the program.
Proper internal documentation ensures that the new programmer will
be able to learn about the program in the least amount of time.

39
Good Internal documentation should include such things as people
who have worked on the program, an abstract of the program, variable
usage, notes about the development of the program, and anything else
that will enable the new programmer to understand this program in the
least amount of time.
5.2.2 EXTERNAL DOCUMENTATION is for the user of the
program. The END USER will use the program to help solve problems.
Proper external documentation ensures that the end user will have
good instructions in order to learn to use this program in the least
amount of time.
External documentation should also allow the end user to find answers
to questions arising while using the program.
Good external documentation increases productivity for the end user.
External documentation should include such things as tutorials, input
definitions, usage instructions, installation instructions, command, and
anything else that will allow the end user to learn to use this program in
the least amount of time.
External documentation may be printed or electronic, such as help
menus. Documentation of your program is very important.
5.3 Testing Solution(Evaluating The Solution)
When your solution is complete, it is important to test it to make sure
there are no errors and it meets the requirements written at the beginning
of the programming process (there are many programs that ‘drift’ away
from their original requirements).

40
To test a solution, the programmer selects test data, a set of values for
the input data of the program, and for each one works methodically
through the instructions of the program. Care must be taken to select the
right data to test it with, as not all input data will test all the functionality
of your program. If any bugs (errors) are identified in your program,
then you should correct them.
For example, if your program requires that a user enter integers, then
what happens if the user enters a character? Your program should be
able to ignore the wrong input and ask again for the correct input (an
integer).
Similarly, when you are dealing with loops or conditionals, you should
be able test if all these behave as you would expect. Typical errors occur
when a wrong number of loops are counted (for example, counting from
0 or 1) or conditionals are badly organised.
5.4 Coding the Solution
Once you have completed the steps described so far, you have finished
analyzing the problem and organizing the solution. The next step is
writing the solution of the problem into a computer language—that is,
coding the solution. You will learn to code solutions when you take
Programming language courses.

41
Chapter Six (6) Software Development Cycle

6. Software Development Cycle


The development of a solution to a problem is a continuing process until
the problem becomes obsolete...is the process of understanding how a
software can support business needs, designing the system, building it,
and delivering it to users.
There are five steps in the software development cycle.
6.1 Analysis of the problem. This includes analyzing the problem to
identify the needed data, the required results, and some ideas of how to
process the data to achieve the desired results. The PAC is used in this
step.
6.2 Design of the solution. This includes deciding what modules to use,
how they interact, and naming the variables. The IPO chart, the
interactivity chart, the coupling diagram, and the data dictionary are
used in this step.
6.3 Development of the solution. This includes the development and
testing of the code for each of the modules. The development of the code
includes the use of algorithms, flowcharts, pseudocode, UML and the
code in the desired computer language. When the program has been
coded in the desired language, the testing begins. Multiple data should
be used to make sure all paths of the program are correct.
6.4 Implementation of the solution. At this point the program is ready
for use. This includes marketing, training, and final testing. Many times

42
it first goes through selected audience to finalize the testing, before it is
released for general use.
6.5 Maintenance and review of the solution. After the program is in
general use, it must be maintained and reviewed often. Maintenance
includes correction of errors found after it was released and minor
updates to the program. The program should be reviewed often. If there
are major updates then the software development cycle starts over. If
after the review, the program is deemed obsolete, then it is taken off the
market.

43

You might also like