Course Title: Problem-Solving (COS102)
Learning Outcomes
At the end of this course, students should be able to:
1. Explain problem-solving processes.
2. demonstrate problem-solving skills;
3. Describe the concept of algorithm development and the properties of algorithms.
4. Discuss the solution techniques for solving a problem.
5. Solve computer problems using algorithms, flowcharts, pseudocode, etc., and
6. Solve problems using the Python programming language.
Course Contents
Introduction to the core concepts of computing. Problems and problem-solving. Identifying
issues and types of problems (routine problems and non-routine problems). Method of solving
computing problems (introduction to algorithms and heuristics). Solvable and unsolvable
problems. Solution techniques of solving problems (abstraction, analogy, brainstorming, trial and
error, hypothesis testing, reduction, literal thinking, means-end analysis, method of focal object,
morphological analysis, research, root cause analysis, proof, divide and conquer). General
Problem-solving process. Solution formulation and design: flowchart, pseudocode, decision
table, decision tree. Implementation, evaluation, and refinement. Programming in Python, etc.
Lab Work: Use of simple tools for algorithms and flowcharts; writing pseudocode; writing
assignment statements, input-output statements, and condition statements; demonstrating simple
programs using any programming language (Visual Basic, Python, C)
TOPIC 1: INTRODUCTION TO THE CORE CONCEPTS OF COMPUTING
1.1 What is Computing?
Computing is the study and use of computer systems to process data, solve problems, and
automate tasks. It involves hardware, software, algorithms, and programming to achieve efficient
and effective solutions. Computing is the foundation of modern technology and is used in
various fields, including business, science, healthcare, and engineering.
1.2 Core Concepts of Computing
Computing consists of several fundamental concepts that guide its application in problem-
solving:
1. Data and Information Processing – Computing involves collecting, processing, storing,
and retrieving data to produce useful information.
2. Algorithms and Problem-Solving – Algorithms are step-by-step instructions that
computers follow to perform tasks. They are essential for solving problems efficiently.
3. Programming – Programming involves writing code in languages like Python, Java, and
C++ to implement algorithms and automate processes.
4. Computer Hardware and Software – Computing systems consist of physical
components (hardware) and software programs that allow them to function.
5. Networking and Communication – Computers communicate over networks to share
information and resources, leading to the development of the internet and cloud
computing.
6. Artificial Intelligence (AI) and Machine Learning – AI enables computers to learn
from data and perform intelligent tasks, such as voice recognition and image processing.
1.3 Features of Computing
Automation – Computers can perform repetitive tasks efficiently.
Speed – Computing systems process data quickly, reducing human effort.
Accuracy – Computational processes minimize errors in calculations and operations.
Versatility – Computers can be programmed to perform various tasks across different
fields.
Connectivity – Networking allows seamless communication and data sharing.
1.4 Applications of Computing
Education – E-learning platforms, online libraries, and virtual labs.
Healthcare – Medical diagnosis, patient records management, and robotic surgeries.
Business – Data analysis, automation of transactions, and online marketing.
Engineering – Computer-aided design (CAD) and simulations.
Entertainment – Video games, animation, and music production.
1.5 Example of Computing in Action
Consider an online shopping system:
A user places an order on a website (data processing).
The system calculates the price and updates the stock (algorithms).
The payment is processed securely (networking and security).
A confirmation email is sent to the user (automation).
TOPIC 2: PROBLEMS AND PROBLEM-SOLVING
2.1 What is a Problem?
A problem is a challenge or difficulty that requires a solution. Problems can be encountered in
various aspects of life, including business, science, technology, and daily activities.
2.2 Problem-Solving in Computing
Problem-solving is the process of finding solutions to complex challenges. In computing, it
involves breaking down a problem, analyzing it, and applying systematic methods to find a
solution using algorithms and programming techniques.
2.3 Steps in Problem-Solving
The process of solving problems in computing typically involves:
1. Understanding the Problem – Identify and define the issue clearly.
2. Breaking Down the Problem – Divide it into smaller, manageable parts.
3. Exploring Possible Solutions – Consider different approaches to solving the problem.
4. Choosing the Best Solution – Select the most efficient and feasible solution.
5. Implementing the Solution – Use programming languages and algorithms to develop
the solution.
6. Testing and Debugging – Identify and fix errors to ensure accuracy.
7. Evaluating the Solution – Analyze whether the solution meets the required needs.
2.4 Features of Effective Problem-Solving
Logical Reasoning – Ability to approach problems systematically.
Creativity – Thinking of innovative solutions.
Analytical Thinking – Evaluating different aspects of the problem.
Persistence – The ability to refine and optimize solutions.
2.5 Applications of Problem-Solving in Computing
Software Development – Writing efficient programs to automate tasks.
Cybersecurity – Identifying and fixing security vulnerabilities.
Data Analysis – Using algorithms to extract useful insights from data.
Artificial Intelligence – Training machines to solve problems independently.
2.6 Example of Problem-Solving in Computing
A banking application may need to detect fraudulent transactions. The problem-solving process
would involve:
Identifying patterns of fraudulent activity.
Designing an algorithm to flag suspicious transactions.
Implementing the algorithm in a banking system.
Testing and refining the solution for better accuracy.
Real-World Example of Problem-Solving in Computing
Scenario: A Website is Loading Too Slowly
Imagine you have a website, but when people visit it, it takes a long time to load. This is a
problem because users might leave before the website even opens.
Step-by-Step Problem-Solving Approach
1. Identify the Problem:
The website takes too long to load.
Users complain or leave before the page opens.
2. Gather Information:
Use tools like Google PageSpeed Insights or GTmetrix to analyze loading speed.
Check internet connection speed.
Inspect the website’s code for large images, too many scripts, or unnecessary elements.
3. Develop Possible Solutions:
Reduce image sizes (compress them).
Minimize or remove unnecessary JavaScript and CSS files.
Enable browser caching so that returning visitors load pages faster.
Use a Content Delivery Network (CDN) to load content from servers closer to users.
4. Implement a Solution:
Compress large images using tools like TinyPNG.
Minify JavaScript and CSS to remove extra spaces and comments.
Enable caching through the website’s settings.
5. Test the Solution:
Reload the website and check if it opens faster.
Use speed test tools again to confirm improvements.
6. Evaluate and Maintain:
If the speed is still slow, try other solutions like upgrading the web hosting plan.
Regularly monitor the website to ensure it stays fast.
Outcome:
Following this structured problem-solving approach makes the website faster, improving user
experience and keeping visitors engaged. This example demonstrates how computing
professionals approach problems logically and systematically. Would you like a different
example, maybe in programming or cybersecurity?
TOPIC 3: THE IDENTIFICATION OF PROBLEMS AND TYPES OF PROBLEMS
3.1 Identifying Problems
Identifying a problem is the first step in problem-solving. A well-identified problem should be:
Clearly defined – The issue must be understood in detail.
Measurable – The impact of the problem should be quantifiable.
Feasible to solve – A solution must be achievable within available resources.
3.2 Types of Problems
Problems can be categorized based on complexity and how frequently they occur:
3.2.1 Routine Problems
Routine problems are common and occur frequently in similar conditions. These problems often
have predefined solutions and can be solved using standard procedures or algorithms.
Features of Routine Problems:
Occur regularly and have predictable solutions.
Solved using well-defined procedures.
Require minimal creativity as solutions are standard.
Examples of Routine Problems in Computing:
Sorting a list of numbers.
Searching for an item in a database.
Logging into a system using a username and password.
Application of Routine Problem-Solving:
Automated customer service bots use predefined responses to handle common
inquiries.
Sorting algorithms like Bubble Sort and Quick Sort organize data efficiently.
3.2.2 Non-Routine Problems
Non-routine problems are complex and do not have a straightforward solution. They require
creative thinking, experimentation, and new strategies to solve problems.
Features of Non-Routine Problems:
Require critical thinking and innovation.
Solutions are not immediately obvious.
May involve trial and error to find the best approach.
Examples of Non-Routine Problems in Computing:
Developing an artificial intelligence system that mimics human speech.
Creating a new encryption algorithm to protect online transactions.
Designing a software system that can predict disease outbreaks.
Application of Non-Routine Problem-Solving:
Machine Learning algorithms are trained to detect fraudulent activities dynamically.
Cybersecurity experts develop new methods to counter emerging cyber threats.
4.0 METHODS OF SOLVING COMPUTING PROBLEMS (INTRODUCTION TO
ALGORITHMS AND HEURISTICS)
Computing problems are solved using structured approaches that ensure efficiency and accuracy.
Two primary methods for solving problems in computing are algorithms and heuristics. These
methods are used based on the nature of the problem, required efficiency, and available
computational resources.
4.1 Algorithms: A Structured Approach to Problem-Solving
An algorithm is a well-defined, step-by-step procedure or set of rules used to solve a specific
problem. It is a fundamental concept in computer science and serves as the basis for
programming and computation.
Features of an Algorithm
A good algorithm should have the following properties:
Input – It takes zero or more inputs.
Output – It provides at least one output.
Definiteness – Each step must be clearly and precisely defined.
Finiteness – The algorithm must terminate after a finite number of steps.
Correctness – It must solve the problem correctly.
Efficiency – It should be optimized for time and space.
Applications of Algorithms
Algorithms are widely used in:
Sorting and Searching (e.g., Bubble Sort, Binary Search)
Data Processing (e.g., Compression, Encryption)
Artificial Intelligence (e.g., Machine Learning Algorithms)
Graph Traversal (e.g., Dijkstra’s Algorithm for shortest path)
Example: Algorithm to Find the Sum of Two Numbers
1. Start
2. Input two numbers
3. Add the numbers
4. Display the sum
5. Stop
Python Implementation
# Define a function named add_numbers that takes two parameters: a and b
def add_numbers(a, b):
# Return the result of adding a and b
return a + b
# Ask the user to input the first number, convert it from a string to an integer, and store it in the
variable num1
num1 = int(input("Enter first number: "))
# Ask the user to input the second number, convert it from a string to an integer, and store it in
the variable num2
num2 = int(input("Enter second number: "))
# Call the add_numbers function with num1 and num2 as arguments,
# Then print the result with a message
print("The sum is:", add_numbers(num1, num2))
4.2 Heuristics: An Approximate Approach to Problem-Solving
A heuristic is a problem-solving method that finds a satisfactory solution where finding an
optimal solution is impractical due to complexity or time constraints. Unlike algorithms,
heuristics do not guarantee a perfect solution but aim to find a "good enough" solution quickly.
Features of Heuristics
Speed – Provides a fast solution rather than an optimal one.
Flexibility – Can be applied to a wide range of problems.
Trade-off between accuracy and efficiency – May not guarantee correctness.
Applications of Heuristics
Artificial Intelligence – Used in decision-making systems.
Game Playing – Chess engines use heuristics to evaluate board positions.
Route Optimization – GPS systems use heuristics for traffic-aware routing.
Scheduling Problems – Used in job scheduling and resource allocation.
Example: Heuristic Approach in Route Optimization
Instead of evaluating every possible path in a city, a heuristic approach might prioritize:
Shortest distance first
Avoiding high-traffic areas
Preferring highways over local roads
TOPIC 5.0 SOLVABLE AND UNSOLVABLE PROBLEMS IN COMPUTING
Not all problems in computing have a solution. Problems are classified into solvable and
unsolvable categories based on whether an algorithm exists that can provide an answer within
finite time and resources.
5.1 Solvable Problems
A solvable problem is one for which an algorithm can be designed to provide a correct solution
within a reasonable amount of time and space.
Examples of Solvable Problems
Sorting Numbers – Sorting a list of numbers using the Quick Sort algorithm.
Pathfinding – Finding the shortest route using Dijkstra’s algorithm.
Data Compression – Reducing file size using Huffman coding.
Matrix Multiplication – Performing mathematical operations on matrices.
Python Example: Solving the Sorting Problem Using Bubble Sort
# Define a function called bubble_sort that takes a list 'arr' as input
def bubble_sort(arr):
# Get the number of elements in the list
n = len(arr)
# Outer loop runs n times to make sure all elements are sorted
for i in range(n):
# Inner loop goes from 0 to n-i-1
# This ensures that with each pass, the largest element "bubbles up" to the end
for j in range(0, n-i-1):
# Compare the current element with the next one
if arr[j] > arr[j+1]:
# If the current element is greater, swap them
arr[j], arr[j+1] = arr[j+1], arr[j]
# This is called tuple unpacking — a neat way to swap values
# After sorting is done, return the sorted list
return arr
# Define a list of unsorted numbers
numbers = [64, 25, 12, 22, 11]
# Call the bubble_sort function and store the sorted list in 'sorted_numbers'
sorted_numbers = bubble_sort(numbers)
# Print the result
print("Sorted list:", sorted_numbers)
5.2 Unsolvable Problems
An unsolvable problem is a problem for which no algorithm can be written to provide a correct
solution in all cases. These problems usually arise in computability theory, where a problem
cannot be solved using any computational model.
Examples of Unsolvable Problems
The Halting Problem – Determining whether a given program will eventually stop or
run forever is undecidable.
Tiling Problem – Given a set of tiles, deciding whether they can perfectly tile an infinite
plane is an unsolvable problem.
Post Correspondence Problem (PCP) – A decision problem that cannot be solved
algorithmically.
The Halting Problem (Proven Unsolvable by Alan Turing)
The halting problem asks whether a given program will terminate or continue to run indefinitely.
Turing proved that it is impossible to write a program that can determine this for all cases.
Python Representation of an Unsolvable Problem (Halting Problem Simulation)
def will_halt(program, input_value):
try:
exec(program)
return "Program halts"
Except:
Return "Program runs indefinitely"
program_code = """
while True:
Pass # Infinite loop
"""
print(will_halt(program_code, None))
Explanation: The function tries to execute the given program, but if it contains an infinite loop,
it will never stop, making it an unsolvable problem.
TOPIC 6: SOLUTION TECHNIQUES FOR SOLVING PROBLEMS
Problem-solving is a fundamental skill in computer science, where various techniques are used to
analyze and resolve complex issues. Selecting the right solution technique depends on the nature
of the problem. This note explores different solution techniques, their features, applications, and
examples.
1. Abstraction
Definition
Abstraction is the process of simplifying a complex problem by removing unnecessary details
and focusing on the essential aspects.
Features
Helps in managing complexity.
Focuses on relevant details while ignoring irrelevant ones.
Commonly used in programming and software design.
Applications
In object-oriented programming (OOP), classes and objects abstract real-world entities.
In database design, abstraction is used in different schema levels (Conceptual, Logical,
Physical).
Example
When designing a mobile app, abstraction helps focus on core functions like user interface and
data handling, without worrying about the hardware details.
2. Analogy
Definition
Analogy involves solving a problem by finding a similar past problem and applying its solution
to the current issue.
Features
Encourages pattern recognition.
Uses past experiences to solve new problems.
Common in artificial intelligence and machine learning.
Applications
Used in AI for case-based reasoning.
Applied in engineering to develop new technologies by modifying existing ones.
Example
The structure of an airplane’s wings was inspired by birds' wings, using the analogy of flight
dynamics.
3. Brainstorming
Definition
Brainstorming is a group or individual problem-solving technique where multiple ideas are
generated to find the best possible solution.
Features
Encourages creative and out-of-the-box thinking.
Focuses on idea quantity before filtering for quality.
Used in business, software development, and research.
Applications
Software development teams brainstorm to generate innovative app features.
Business teams brainstorm to create marketing strategies.
Example
A development team brainstorming ideas for a new mobile banking application.
4. Trial and Error
Definition
Trial and error is a method of solving a problem by repeatedly testing different solutions until the
correct one is found.
Features
Simple and intuitive.
Can be time-consuming and inefficient for complex problems.
Commonly used in learning and scientific research.
Applications
Debugging code in programming.
Chemical experiments in laboratories.
Example
A programmer is debugging a software error by modifying the code multiple times until it runs
correctly.
5. Hypothesis Testing
Definition
Hypothesis testing involves formulating an assumption (hypothesis) and testing it through
experiments or observations.
Features
Involves collecting and analyzing data.
Uses statistical methods to validate or reject hypotheses.
Commonly used in research and decision-making.
Applications
Used in AI and machine learning to train models.
In business, used for market research and trend analysis.
Example
A data scientist is testing whether an increase in social media ads improves product sales.
6. Reduction
Definition
Reduction simplifies a complex problem by breaking it down into a simpler equivalent problem
that is easier to solve.
Features
Converts difficult problems into well-known, solvable ones.
Used in mathematics and computing.
Efficient for optimization problems.
Applications
Used in algorithm design to reduce complex computations.
Applied in cryptography for breaking down encryption techniques.
Example
A complex image processing problem is reduced to a simpler matrix manipulation problem.
7. Literal Thinking
Definition
Literal thinking focuses on a direct and logical approach to solving problems without
assumptions or abstract interpretations.
Features
Straightforward and structured.
Avoids subjective interpretation.
Commonly used in programming and legal reasoning.
Applications
Writing clear and explicit software code.
Legal contracts that require precise wording.
Example
A programmer follows exact specifications in writing a sorting algorithm.
8. Means-End Analysis
Definition
Means-end analysis involves comparing the current state of a problem with the desired goal and
determining the best way to close the gap.
Features
Involves setting subgoals to reach the main goal.
Used in artificial intelligence and robotics.
Helps in planning and decision-making.
Applications
Used in game AI to plan moves in chess.
Applied in navigation systems to find the shortest route.
Example
A GPS determines the shortest path to a destination by comparing the current and target
locations.
9. Method of Focal Object
Definition
This technique involves taking an unrelated object and combining its characteristics with the
problem to generate creative solutions.
Features
Encourages innovation.
Commonly used in product design and engineering.
Helps in creative problem-solving.
Applications
Used in industrial design for new product innovations.
Applied in marketing for unique advertising campaigns.
Example
Using the design of a fish’s gills to develop better air filtration systems.
10. Morphological Analysis
Definition
Morphological analysis involves systematically examining all possible solutions to a problem by
considering multiple dimensions and variations.
Features
Uses a structured framework.
Effective for complex problems with multiple factors.
Applied in engineering, business strategy, and innovation.
Applications
Used in mechanical engineering for new product designs.
Applied in business strategy to evaluate market scenarios.
Example
A car company is analyzing various engine, body, and fuel types to design a new vehicle.
11. Research
Definition
Research involves systematically gathering information, analyzing data, and evaluating evidence
to solve a problem.
Features
Relies on data and factual evidence.
Involves detailed study and analysis.
Common in academia and business.
Applications
Scientific discoveries and technological advancements.
Business market analysis and consumer behavior research.
Example
Researchers study user feedback to improve an e-commerce website for better performance.
12. Root Cause Analysis (RCA)
Definition
Root cause analysis focuses on identifying the underlying reason for a problem rather than just
addressing symptoms.
Features
Provides long-term solutions.
Helps prevent the recurrence of problems.
Used in engineering, healthcare, and software development.
Applications
Debugging software errors by tracing the root cause.
Identifying safety hazards in workplaces.
Example
A network administrator traces repeated system failures to a faulty server component.
13. Proof
Definition
Proof is the process of logically verifying the correctness of a solution using mathematical or
formal reasoning.
Features
Ensures correctness and reliability.
Used in theoretical computer science and cryptography.
Helps in validating algorithms.
Applications
Proving the correctness of an encryption algorithm.
Mathematical proofs in algorithm complexity analysis.
Example
Verifying that a sorting algorithm correctly arranges numbers in ascending order.
14. Divide and Conquer
Definition
Divide and conquer is a problem-solving technique that breaks a large problem into smaller,
independent subproblems, solves them individually, and then combines the solutions.
Features
Improves efficiency.
Used in recursive algorithms.
Common in computer science and engineering.
Applications
Sorting algorithms like Merge Sort and Quick Sort.
Parallel computing and distributed systems.
Example
Sorting a large dataset using Merge Sort, which divides the dataset into smaller sorted segments
and merges them.
Topic 7: GENERAL PROBLEM-SOLVING PROCESS
Introduction
In Computer Science and everyday life, problem-solving is a foundational skill. It involves
identifying an issue, understanding it, and devising a solution. Whether you're writing a
computer program, debugging code, or designing a system, you follow a problem-solving
process. Problem-solving is not guesswork; it's a structured, step-by-step approach to reach a
solution effectively and efficiently.
Key Stages of the Problem-Solving Process
The general problem-solving process typically involves the following steps:
1. Problem Definition (Understanding the Problem)
What it means: Identify what the problem is and what is being asked.
Why it's important: Misunderstanding the problem can lead to wrong or inefficient
solutions.
Example: You are asked to write a program that calculates the average of 5 numbers.
Make sure you understand:
o What type of numbers?
o Will they be entered by a user?
o Is there a specific format?
2. Analyze the Problem
What it means: Break the problem into smaller parts. Understand inputs, outputs,
constraints, and data types.
Why it's important: Helps you identify resources, limitations, and potential methods.
Example: For the average program:
o Inputs: 5 numbers (e.g., integers or floats)
o Output: One number (the average)
o Constraints: Should handle negative numbers? Should avoid division by zero?
3. Develop an Algorithm (Plan the Solution)
What it means: Write a step-by-step procedure to solve the problem.
Why it's important: Algorithms are like blueprints for your program.
Example:
o Step 1: Ask the user to enter 5 numbers
o Step 2: Add all 5 numbers
o Step 3: Divide the sum by 5
o Step 4: Display the result
4. Implement the Solution (Coding)
What it means: Translate the algorithm into a programming language (e.g., Python,
Java, C++).
Why it's important: Code turns your ideas into something that works.
5. Test and Debug
What it means: Run the program and check if it works as expected. Fix any errors.
Why it's important: Ensures the program is accurate and reliable.
Example: Try entering numbers like 0, negative values, or very large values to see how
your code reacts.
6. Document and Maintain
What it means: Add comments, explain your code, and prepare it for future updates.
Why it's important: Helps others (and your future self) understand and use your
solution.
Example: Add a comment above your average calculation to explain why you're dividing
by 5.
🧩 Summary of Steps
Step Description
1. Define the Problem Understand the task clearly
2. Analyze the Problem Identify inputs, outputs, constraints
3. Develop an Algorithm Plan the steps to solve the problem
4. Implement the Solution Write the code
5. Test and Debug Check for errors and fix them
6. Document and Maintain Explain your work for future use
Real-Life Example
Problem: You forget your password often and want a way to store and retrieve it safely.
Problem-Solving Process:
1. Define the Problem: Need a secure way to store passwords.
2. Analyze: Inputs (passwords), Output (retrieve passwords securely), Constraint (must be
secure).
3. Algorithm: Create a password manager app with login, encryption, and search.
4. Implementation: Code using Python + SQLite + encryption.
5. Test: Try storing, retrieving, and deleting entries.
6. Document: Explain how to use the app and how it encrypts data.
Why it Matters in Computer Science
Helps in programming, debugging, and software design
Encourages logical thinking
Makes projects more efficient and reliable
Forms the basis of algorithms and data structures
Conclusion
The general problem-solving process is essential in Computer Science. It promotes clarity,
structure, and effectiveness in tackling both academic and real-world problems. By mastering
these steps, you improve not only your coding skills but also your analytical and creative
thinking abilities.
Topic 8: Solution Formulation and Design: Flowchart, Pseudocode, Decision Table,
Decision Tree
Introduction to Solution Formulation and Design
When solving a computational problem, it is not enough to just understand the problem; you
must also plan how to solve it effectively. Solution formulation and design is the phase in
problem-solving where logical steps, decisions, and processes are organized before
implementation in a programming language. This planning stage uses various tools to visualize
and structure the logic of a solution. These tools include:
Flowcharts
Pseudocode
Decision Tables
Decision Trees
Flowcharts: Flowcharts use special shapes to represent different types of actions or steps in a
process. Lines and arrows show the sequence of the steps and the relationships among them.
These are known as flowchart symbols. In a flowchart, a rectangle shape represents a process, an
oval or pill shape represents the start or end, a diamond shape represents a decision, and a
parallelogram represents input/output.
Purpose:
To visually outline the steps of a program.
To make complex processes easier to understand.
Pseudocode: It is a term that is often used in programming and algorithm-based fields. It is a
methodology that allows the programmer to represent the implementation of an algorithm.
Simply, we can say that it’s the cooked-up representation of an algorithm. Often at times,
algorithms are represented with the help of pseudo code as they can be interpreted by
programmers, no matter what their programming background or knowledge is. Pseudo code, as
the name suggests, is a false code or a representation of code that can be understood by even a
layman with some school-level programming knowledge.
Purpose:
Bridges the gap between the algorithm and the actual code.
Helps programmers plan before implementation.
Features:
No strict syntax rules.
Easy to understand.
Focused on logic, not syntax.
How to write a Pseudo-code?
1. Arrange the sequence of tasks and write the pseudocode accordingly.
2. Start with the statement of a pseudocode that establishes the main goal or the aim.
Example:
This program will allow the user to check
the number, whether it's even or odd.
1. The way the if-else, for, and while loops are indented in a program, indent the statements
likewise, as it helps to comprehend the decision control and execution mechanism. They
also improve the readability to a great extent.
Example 1:
If "1"
print response
"I am case 1."
If "2"
print response
"I am case 2."
Example 2: Algorithm to find the maximum of two numbers:
START
INPUT A, B
IF A > B THEN
PRINT A
ELSE
PRINT B
END IF
END
Decision Table: A decision table is a tabular method for representing and analyzing decision
logic. It lists different conditions and the corresponding actions to take for each combination of
conditions.
Purpose:
To handle complex decision-making processes.
To reduce ambiguity by showing all possible scenarios.
Structure:
Conditions: Various inputs or logical checks.
Actions: What to do when conditions are met.
Rules: Specific combinations of conditions.
Example: ATM withdrawal scenario
Condition 1: Card Condition 2: PIN Action 1: Allow Action 2: Show
Inserted Correct Withdrawal Error
Yes Yes Yes No
Yes No No Yes
No -- No Yes
Decision Tree: A decision tree is a graphical representation of different options for solving a problem
and shows how different factors are related. It has a hierarchical tree structure that starts with one main
question at the top called a node, which further branches out into different possible outcomes where:
The Root Node is the starting point that represents the entire dataset.
Branches: These are the lines that connect nodes. It shows the flow from one decision to
another.
Internal Nodes are Points where decisions are made based on the input features.
Leaf Nodes: These are the terminal nodes at the end of branches that represent outcomes
or predictions
An example to understand the decision tree: imagine you want to decide whether to drink
coffee based on the time of day and how tired you feel. First, the tree checks the time of
day. If it’s morning, it asks whether you are tired. If you’re tired, the tree suggests
drinking coffee; if not, it says there’s no need. Similarly, in the afternoon, the tree again
asks if you are tired. If you recommend drinking coffee if not it concludes no coffee is
needed.
Classification of Decision Tree: We have mainly two types of decision tree based on the nature
of the target variable: classification trees and regression trees.
Classification trees: They are designed to predict categorical outcomes, meaning they
classify data into different classes. They can determine whether an email is “spam” or
“not spam” based on various features of the email.
Regression trees: These are used when the target variable is continuous It predict
numerical values rather than categories. For example, a regression tree can estimate the
price of a house based on its size, location, and other features.
TOPIC 9: IMPLEMENTATION, EVALUATION, AND REFINEMENT.
9.1 Implementation
Implementation is the stage where the planned solution is translated into code using a
programming language. It brings the abstract plan to life.
Example Problem: Write a program to calculate the sum of the first 10 natural numbers.
Solution (Pseudocode):
initialize sum = 0
for each number from 1 to 10:
Add number to sum
print sum
Python Implementation:
sum = 0
for i in range(1, 11):
sum += i
print("Sum of first 10 natural numbers is:", sum)
9.2 Evaluation
Evaluation checks how well the solution meets the requirements and how efficient or correct it
is.
Evaluation Criteria:
Correctness: Does the program produce the right output?
Efficiency: How fast and memory-efficient is the program?
Robustness: Can the program handle unexpected inputs?
Readability: Is the code easy to read and maintain?
Example: If the user inputs a number instead of using a fixed range:
n = int(input("Enter a number: "))
sum = 0
for i in range(1, n+1):
sum += i
print("Sum is:", sum)
9.3 Refinement
Refinement involves improving the solution based on the evaluation. It could include:
Removing bugs
Optimizing for performance
Making the user interface better
Adding input validation
Refinement Example:
Original Code:
n = int(input("Enter a number: "))
sum = 0
for i in range(1, n+1):
sum += i
print("Sum is:", sum)
Refined code with input validation:
try:
n = int(input("Enter a positive number: "))
if n < 1:
print("Number must be positive.")
else:
sum = 0
for i in range(1, n+1):
sum += i
print("Sum is:", sum)
except ValueError:
print("Invalid input! Please enter a valid integer.")