COS102 Lecture Note
COS102 Lecture Note
1. Course Objectives
1. To Explain problem solving process
2. To Explain the skills required in problem solving
3. To Explain the techniques of solving problems
4. To Explain the concept of Algorithms and its properties
5. To Explain how to solve computer problems using different algorithm
implementations
6. To solve computer problems using programming languages
2. Learning Outcomes
At the end of this course, students should be able to:
1. Explain Algorithm and problem solving processes;
2. Demonstrate problem solving skills;
3. Describe the concept of algorithms development and properties of algorithms;
4. Discuss the solution techniques of solving problem;
5. Solve computer problems using algorithms, flowcharts, pseudocode; etc.; and
6. Solve problems using programming language using PYTHON, C++, Java, etc.
1
MODULE 1
Introduction
Problem-solving is a basic cognitive skill that is important in all fields. Whether you
want to be an engineer, scientist, business analyst, or computer programmer, you
need to be able to deal with difficult problems and come up with good solutions. This
is the key to success in almost any field. In this introduction, we will discuss what
problem-solving is and why it is important. We will also lay the fundation for the
methods and techniques that will guide us through the rest of the course.
Innovation and Progress: Many of humanity's greatest achievements have been the
result of innovative problem solving. From the invention of the wheel to landing
humans on the moon, solving complex problems has driven progress throughout
history. Innovators and inventors are essentially problem solvers who identify
challenges and create solutions.
Career Success: In the professional world, problem-solving skills are highly valued.
Employers seek individuals who can address challenges and find solutions efficiently.
Regardless of the industry or job role, problem solvers are more likely to excel in
their careers. They can adapt to changing circumstances, identify opportunities for
improvement, and contribute positively to their organizations.
2
others to achieve common goals. Effective communication is vital in team
environments and leadership roles.
For Instance: You are trying to figure out why your computer won't turn on. You
realize that it is not a power issue because the lights are on, but the screen remains
black. Understanding the problem requires identifying potential causes, such as a
disconnected monitor cable or a faulty graphics card.
3
complete solution. This approach is particularly useful for tackling large and intricate
challenges and it is known as modularization. This form the basis for structured
programming.
Example: You have a big pile of laundry to do. Instead of tackling it all at once, you
divide the task into sub-problems: sort clothes by type, wash, dry, fold, and put them
away. By addressing each step separately, you make the laundry task more
manageable. Each of the sub-problem can be undertaken by different person or
machine thereby making the work faster.
3. Brainstorming
Gather a group of people, if possible, and engage in brainstorming sessions.
Encourage the generation of as many ideas and potential solutions as possible,
without criticism at this stage. Brainstorming can spark creative thinking and lead to
innovative solutions.
Example: You and your friends are deciding what movie to watch. Everyone suggests
different idea and films. Brainstorming generates a list of movie options to consider.
Example: You are solving a jigsaw puzzle. You try different pieces in various positions
until you find the one that fits correctly.
Example: You are playing a game of Tic-Tac-Toe, and you notice that every time your
opponent starts in the center, they win. Recognizing this pattern, you decide to start
in the center in your next game to test whether it improves your chances.
6. Analogies
Analogical thinking involves drawing parallels between the current problem and
similar problems you have encountered or heard of in the past. By recognizing
similarities, you can adapt solutions from previous experiences to the current
problem.
4
select a programming language (e.g., Python, Java, or C++) based on the task at hand.
Each language has its strengths and weaknesses, just like vehicles do.
8. Ask Questions
Ask a series of well-defined questions to systematically analyze the problem.
Questions like "What is the root cause?" or "What are the possible solutions?" can
guide your thinking and decision-making process.
Example: You are troubleshooting why your smartphone battery drains quickly.
Questions like "Which apps are consuming the most battery?" and "Is the screen
brightness too high?" help you identify the issue.
Example: You have a busy day ahead with multiple tasks to complete. You prioritize
your tasks by urgency and importance, creating a to-do list and planning your day
accordingly.
Example: You have written an essay for school. You ask a friend to review it and
provide feedback on grammar, clarity, and overall quality to improve your writing.
Example: You are trying to solve a challenging Sudoku puzzle. If your initial number
placements don't lead to a solution, you erase and try different numbers until you
successfully complete the puzzle.
5
An algorithm is a step-by-step procedure for solving a specific problem. Algorithms
provide a structured framework for problem solving. When applicable, search for or
develop algorithms that are relevant to the problem you're facing. Algorithms can
range from mathematical formulas to logical decision trees.
Example: You want to make a peanut butter and jelly sandwich. The algorithm is a set
of specific steps: spread peanut butter on one slice of bread, spread jelly on another
slice, press the slices together, and cut the sandwich diagonally into two triangles.
6
13. Use Technology
Leverage technological tools and software, such as data analysis software,
simulations, or specialized problem-solving apps, to assist in your problem-solving
efforts.
Example: You are calculating your monthly budget. Instead of doing it manually, you
use spreadsheet software to perform the calculations and create visual
representations of your financial data.
Example: Imagine you're a computer programmer. You use computer science ideas
to come up with cool new features for computer programs. Understanding the
programming language the coding involved during programming (coding) allows
you to come up with the new features for computer programs.
Example: After struggling with a math problem, you review your approach and
realize you made an error in calculations. Reflecting on your mistake, you correct it
and learn from it to avoid similar errors in the future.
7
MODULE 2
Problem Solving Process
Problem solving involves several steps, which can vary slightly depending on the
type and nature of the problem. Here are Eight general steps in problem solving:
Step 1: Define the Problem- What is the problem? The first step is to clearly
understand the problem. This involves gathering requirements (e.g. input and
output), defining objectives, and understanding user needs.
Step 2: Analyze the problem that is, Clarify the problem.
Step 3: Develop potential solutions.
Step 4: Evaluate the options; if there are more than one possible solution
Step 5: Select the best Option.
Step 6: Implement the Solution.
Step 7: Measure the Results.
1. Active Listening and good information processing skill. Poor communication can
lead to misunderstandings and lack of clarity and direction – which, in turn, can
be detrimental to team performance.
2. Analytical thinking
3. Creative thinking
4. Collaborative communication skill
5. Decision-making skill
6. Teamwork
7. Persistence
8. Coachability
MODULE 3
8
The Concept of Algorithms
Algorithms are precise step-by-step instructions for solving problems. They provide
a clear and unambiguous path to achieving a specific goal. Algorithms are
independent of programming languages; the same algorithm can be implemented in
different languages. Writing efficient algorithms is essential for optimizing program
performance and resource usage.
Properties of Algorthms
1. Finiteness: It must have a finite number of steps. It should start and end
somewhere and not loop endlessly. The algorithm must stop, eventually.
Stopping may mean that you get the expected output OR you get a response
that no solution is possible
2. Effectiveness: For an algorithm to be effective, it means that all those steps that
are required to get to output must be feasible. An algorithm should be feasible;
feasibility indicates that it is practical and capable of being executed.
Effectiveness refers to the ability of an algorithm to consistently and accurately
produce a meaningful and correct result for all possible valid inputs.
3. Definiteness: Algorithms must specify every step and the order the steps must
be taken in the process. The property of definiteness ensures that the agent
executing the instructions will always know which command to perform next.
4. Input: An algorithm should have 0 or more well-defined inputs from a specified
set. That is, An algorithm can have zero or more inputs. This means that there
can be algorithms with no input at all, just one input, or multiple inputs.
5. Output: An algorithm should have 1 or more well-defined outputs, and should
match the desired output. An algorithm must specify the output and how it is
related to the input.
6. Independent: An algorithm should have step-by-step directions, which should
be independent of any programming code. It should be such that it could be
implemented in any programming language and run on any machine.
7. Efficiency: Efficiency is often the measurable ability to avoid making mistakes
or wasting materials, energy, efforts, money, and time while performing a task.
In a more general sense, it is the ability to do things well, successfully, and
without waste. Running time and memory are bounded resources, and our
9
algorithms must use them wisely. In simple words, our algorithm should be
efficient in terms of speed/running time and space/memory.
8. Correctness: Correctness guarantees that the algorithm produces the
predicted output for all possible inputs. That is, if you choose to run the
algorithm for a number of time, it will produce the same result.
9. Unambiguous: Algorithm should be clear and unambiguous. An instrunction
must not imply multiple meaning.
10. Deterministic: An algorithm should be deterministic, meaning that it will
produce the same output for the same input every time it is executed. There
should be no randomness or unpredictability.
11. Termination: The algorithm should always terminate, even if it encounters
unexpected inputs or errors. It should not enter an infinite loop or get stuck.
12. Ease of Understanding: Algorithms should be designed with human
readability in mind. They should be clear, well-structured, and easy to
understand by other programmers.
Step1: Identify the input: For an algorithm, there are quantities to be supplied called
input and these are fed externally. The input is to be identified first for any specified
problem.
Step2: Identify the output: From an algorithm, at least one quantity is produced,
called output for any specified problem.
Step5: Processing Finiteness: If we go through the algorithm, then for all cases, the
algorithm should terminate after a finite number of steps.
10
1. Pseudocode
2. Flowchart
3. Program
Advantages of Pseudocode
Pseudocode offers several advantages in the software development process:
11
• Efficiency and Productivity: Writing pseudocode before coding can lead to
more efficient development. Developers can identify potential issues, design
flaws, or algorithmic inefficiencies early in the process, reducing the need for
later revisions.
• Teaching and Learning: Pseudocode is often used in educational settings to
teach programming concepts, problem-solving skills, and algorithmic
thinking. It helps beginners grasp fundamental programming logic without the
distractions of a specific programming language.
• Code Independence: Pseudocode encourages developers to think
algorithmically rather than focusing on specific code constructs. This can lead
to more flexible and adaptable solutions that are not tied to a particular coding
language.
• Debugging Aid: When problems arise during coding, pseudocode can serve
as a reference for understanding the intended logic. It can help pinpoint issues
and inconsistencies in the code.
• Planning and Design: Pseudocode is a crucial tool during the planning and
design phase of software development. It allows developers to map out the
structure and behavior of a program or algorithm before writing actual code.
• Cross-Functional Communication: Pseudocode can facilitate communication
between technical and non-technical stakeholders, such as project managers,
clients, or domain experts, by providing a high-level view of how a solution will
work.
10 Read n1, n2
20 Sum = n1 + n2
30 Diff = n1 – n2
40 Mult = n1 * n2
50 Quot = n1/n2
60 Print sum, diff, mult, quot
70 End
Key flowchart symbols include rectangles for processes or actions, diamonds for
decisions or conditional statements, arrows for flow direction, and parallelograms for
inputs/outputs.
12
Advantages of Flowcharts
Flowcharts offer several advantages in various fields and applications due to their
visual and structured nature. Here are some of the key advantages of using flowcharts:
13
• Project Management: Flowcharts are used in project management to represent
project workflows, task dependencies, and critical paths. They assist in project
planning and scheduling.
• Documentation Compliance: In regulated industries such as healthcare and
finance, flowcharts can help organizations demonstrate compliance with
industry standards and regulations.
• Process Automation: Flowcharts can serve as blueprints for automating
processes with software or robotic process automation (RPA). They provide a
clear roadmap for automation developers.
• Continuous Improvement: Flowcharts can be updated and revised as processes
evolve or improve over time. They support on-going efforts to enhance
efficiency and effectiveness.
Oval: Rectangle with rounded sides is used to indicate either START/ STOP of the
program.
Parallelograms: are used to represent input and output operations. Statements like
INPUT, READ and PRINT are represented in these Parallelograms.
Rectangle: is used to indicate any set of processing operation such as for performing
arithmetic operations.
Diamond: is used for indicating the step of decision making and therefore known as
decision box. Decision boxes are used to test the conditions or ask questions and
depending upon the answers, the appropriate actions are taken by the computer. The
decision box symbol is
14
Flow Lines: Flow lines indicate the direction being followed in the flowchart. In a
Flowchart, every line must have an arrow on it to indicate the direction. The arrows
may be in any direction.
On- Page connectors: Circles are used to join the different parts of a flowchart and
these circles are called on-page connectors. The uses of these connectors give a neat
shape to the flowcharts. In a complicated problem, a flowchart may run in to several
pages. The parts of the flowchart on different pages are to be joined with each other.
The parts to be joined are indicated by the circle.
Excercise4:
Write the algorithm and draw the flowchart to find Roots of Quadratic equation ax2+
bx + c = 0. The coefficients a, b, c are the input data
Problem5:
Draw a flowchart for adding the integers from 1 to 100 and to print the sum.
15
Problem6:
Draw a flowchart to find the factorial of given positive integer N.
Problem6:
ABC Company plans to give a 6% year-end bonus to each of its employees earning
$6,000 or more per month, and a fixed $250 bonus to the remaining employees. Draw
a flowchart for calculating the bonus for an employee.
16
Student Homework: Identify and draw Ten Flowchart symbols aside the ones listed
here as available in Microsft Word.
Let us bring the three ways to express an algorithm together with an example.
Example 1:
17
Solution 1: Psedocode
Step1: Start
Step2: Read the three numbers a, b, c
Step3: Compute the sum of a, b and c
Step4: Store the sum in S
Step5: Divide the sum in S by 3
Step6: Store the result in A
Step7: Print the value in A
Step8: Stop
Solution 2: Flowchart
Start
Read a, b, and c
S=a+b+c
A = S/3
Print A
Stop
Solution 3: Program
In this case, we have to determine which programming language to use in the implementation
of our algorithm. Suppose we choose to use C++, the program will look like;
18
#include<iostream.h>
int main(){
float a, b, c, S, A;
cout<<”take the three numbers; a, b, and c”;
cin>>a, b, c <<endl;
S = a+b+c;
A = S/3;
cout<<”the average of the three numbers is ”<<A<<endl;
return 0;
}
Take note of how the three different implementations optimizes the algorthm by compressing/
collapsing some steps. E.g. in the flowchart implementation, steps 3 and 4 and steps 5 and 6
of the pseudocode can be combined respectively. Also observe the properties of algorithms
demonstrated in the three algorithm implementations of the same problem.
Exercise 1:
Write an algorithm to calculate the simple interest using the
formula.
Simple interest = P*T* R/100
Where P is Principal Amount, T is the period and R is the rate of
interest.
Exercise 2:
Write an algorithm to find the area of the triangle with a given
angle. Using Area of Triangle = ½*b*C*sinA
Solution to example 2:
Step1: Start program
Step2: Input the given elements of the triangle namely sides b,
c and angle between the sides A.
Step3: Calculate Area of a Triangle = (1/2)*b*C*sinA
Step4: Print the Area of a Triangle
Step5: Stop
Example 3:
Write an algorithm to find the largest of three numbers X, Y, Z.
Solution to example 3:
19
Step7: End program
Exercise 2:
Write an algorithm to find the smallest of three numbers X, Y,Z.
Example 4:
Write a Pseudocode to calculate the perimeter and area of
rectangle, given its length and width.
Solution to example 4:
Step1: Start program
Step2: Read length of the rectangle
Step3: Read width of the rectangle
Step4: Calculate perimeter of the rectangle using the formula
perimeter = 2*(length + width)
Step5: Calculate area of the rectangle using the formula area =
length*width
Step6: Print perimeter
Step7: Print area
Step8: End Program
20
MODULE 4
Control Structures
There are three fundamental structures that are used for the algorithmic resolution of
problems:
Selections control structure: The selection control structure, also known as the
conditional control structure, is a fundamental programming concept that allows a
21
program to make decisions and choose different paths of execution based on certain
conditions or criteria.
One-Way Selection
A bank wants to send a notice to a customer if her or his account balance falls below
the required minimum balance. That is, if the balance is below the required minimum,
the bank should send a notice to the customer; otherwise, it should do nothing.
Similarly, if the policyholder of an insurance policy is a non-smoker, the company
wants to apply a 10% discount to the policy premium. Both of these examples involve
one-way selection. In most programming languages, one-way selections are
incorporated using the if statement.
if (logical expression)
statement
The logical expression is also called a condition; it decides whether to execute the
statement that follows it. If logical expression is true, the statement executes. If it is
false, the statement does not execute and the computer goes on to the next statement
in the program. The statement following the logical expression is sometimes called
the action statement. (Note the indentation of the action statement. We have indented
it four spaces to the right of the if statement in the previous line.)
Figure below shows the flow of execution of the if statement (one-way selection).
grade = 'A';
22
In this code, if the logical expression, score >= 90, evaluates to true, the assignment
statement, grade = 'A';, executes. If score >= 90 evaluates to false, the assignment
statement, grade = 'A';, is skipped. For example, if the value of score is 95, the value
assigned to the variable grade is A.
Two-Way Selection
if (logical expression)
statement1
else
statement2
The structure begins with the word if, followed by a logical expression contained
within parentheses, followed by a statement, followed by the word else, followed by
a second statement. Statements 1 and 2 can be any valid program statements. In a two-
way selection, if the value of the logical expression is true, then statement1 executes.
If the value of the logical expression is false, then statement2 executes.
Figure below shows the flow of execution of the if. . .else statement (two-way
selection).
23
Consider the following statements:
If the value of the variable hours is greater than 40.0, then the wages include overtime
payment. Suppose that hours is 50. The logical expression in the if statement in Line 1
evaluates to true, so the statement in Line 2 executes. On the other hand, if hours is 30,
or any number less than or equal to 40, the logical expression in the if statement in
Line 1 evaluates to false. In this case, the program skips the statement in Line 2 and
executes the statement in Line 4—that is, the statement following the reserved word
else executes.
The while loop is an example of the pre-test loop and has the general form:
The logical expression is called a loop condition or simply a condition. The statement
is called the body of the loop. Moreover, the statement can be either a simple or
compound statement. Also, note that the parentheses around the logical expression
24
are part of the syntax. The figure below shows the flow of execution of a pre-test
(while) loop.
The logical expression provides an entry condition. If it initially evaluates to true, the
statement executes. The loop condition—the logical expression—is then re-
evaluated. If it again evaluates to true, the statement executes again. The statement
(body of the loop) continues to execute until the logical expression is no longer true.
A loop that continues to execute endlessly is called an infinite loop. To avoid an infinite
loop, make sure that the loop’s body contains one or more statements that ensure that
the loop condition—the logical expression in the while statement—will eventually be
false.
Example:
25
Solution:
START
Set temperature_count to zero
while (temperature_count < 15)
Prompt for f_temp
Get f_temp
Compute c_temp = (f_temp - 32)* 5/9
Display c_temp
Increment temperature_count
END while
Display ‘All temperatures processed’ to the screen
END
Counted loops
• Execute the statement block a pre-determined number of times
– Number of iterations known in advance
• A control variable keeps count of the number of repetitions
– No need to change this explicitly in code
• May use i, j & k as control variables (historical)
– meaningful names better
26
• FOR counter=m to n (algorithms)
• FOR (counter=m; counter<=n; m++) (C, C++, Java)
Example:
Rewrite the Fahrenheit_Celsius_conversion algorithm to use the
counted loop.
START
FOR temperature_count = 1 to 15
Prompt operator for f_temp
Get f_temp
Compute c_temp = (f_temp - 32)* 5/9
Display c_temp
END FOR
Display ‘All temperatures processed’ to the
screen
END
Exercise
a = p(1+r)n
27
Step 1: LARGE = 0
Step 2: read NUM
Step 3: While NUM > = 0 do
3.1 if NUM > LARGE
3.1.1 then
3.1.1.1 LARGE = NUM
3.2. read NUM
Step 4: Write “largest data value is”, LARGE
Step 5: end
Step 1: PROD = 1
Step 2: I = 0
Step 3: read N
Step 4: While I < N do
4.1 I = I + 1
4.2. PROD = PROD* I
Step 5: Write “Factorial of”, N, “is”, PROD
Step 6: end
28
4. Write an algorithm to compute sum of given data values until negative value is entered.
Step 1: SUM = 0
Step 2: I = 0
Step 3: read NEWVALUE
Step 4: While NEWVALUE >= 0 do
4.1 SUM = SUM + NEWVALUE
4.2 I = I + 1
4.3 read NEWVALUE
Step 5: Write “Sum of”, I, “data value is, “SUM
Step 6: END
29