CSC 102 Lecture Note
CSC 102 Lecture Note
Faculty Of Science
Department Of Computer Science
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.
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.
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
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
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
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.
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?
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: 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.
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.
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:
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
Solution 2:
Detailed Algorithm
Step 1: Input Lft
Step 2: Lcm Lft x 30
Step 3: Print Lcm
Solution 3:
Detailed Algorithm
Step 1: Input W,L
Step 2: AL 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.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)
Solution 3:
Pseudocode
Input the width (W) and Length (L) of a rectangle
Calculate the area (A) by multiplying L with W
Print A
28
Chart.
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.
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
34
Program flowchart for Example 3 above
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”);
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;
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.
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
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