0% found this document useful (0 votes)
14 views

COS102 Lecture Note

The document outlines a course on Problem Solving and Algorithms, detailing its objectives, learning outcomes, and the importance of problem-solving skills across various fields. It discusses effective problem-solving strategies, the concept and properties of algorithms, and the steps involved in algorithm development. Additionally, it emphasizes the significance of critical thinking, creativity, and collaboration in enhancing problem-solving abilities.

Uploaded by

abdulahibarakah
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)
14 views

COS102 Lecture Note

The document outlines a course on Problem Solving and Algorithms, detailing its objectives, learning outcomes, and the importance of problem-solving skills across various fields. It discusses effective problem-solving strategies, the concept and properties of algorithms, and the steps involved in algorithm development. Additionally, it emphasizes the significance of critical thinking, creativity, and collaboration in enhancing problem-solving abilities.

Uploaded by

abdulahibarakah
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/ 29

COS102: PROBLEM SOLVING AND ALGORITHMS

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.

What is Problem Solving?


Problem-solving is the process of finding solutions to problems or answers to
questions. These questions or challenges can be about anything, from simple daily
jobs to complicated global problems. Problem-solving is a skill that can be used in
any field. It is a universal skill that people have developed and improved over many
years.

Importance of Problem Solving


Problem solving is a fundamental cognitive skills that is extremely important in
personal as well as professional life. It is a skill that cross boundaries and may be
applied in a variety of contexts. Understanding the significance of problem-solving
allows us to understand its role in our everyday lives as well as its impact on society
as a whole. The following are some of the reasons why problem-solving is important;

Critical Thinking: Problem solving is the cornerstone of critical thinking. It involves


the ability to think analytically, evaluate information, and make informed decisions.
Critical thinking skills are vital in academic pursuits, professional settings, and
personal life. Individuals who excel at problem solving tend to be better at critical
thinking, making them more effective decision-makers.

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.

Effective Communication: Problem solvers often excel in effective communication.


They can articulate their thoughts, present their solutions clearly, and collaborate with

2
others to achieve common goals. Effective communication is vital in team
environments and leadership roles.

Personal Growth and Resilience: Overcoming challenges and solving problems


fosters personal growth and resilience. It builds confidence in one's abilities and
provides a sense of accomplishment. People who successfully navigate difficulties are
better prepared to face future obstacles with a positive attitude.

Societal Impact: On a broader level, the collective problem-solving capacity of a


society plays a crucial role in its progress. Societies that encourage and nurture
problem-solving skills tend to be more innovative and adaptable. They can address
complex issues, such as climate change, healthcare, and poverty, with more effective
solutions.

Global Problem Solving: In our interconnected world, global challenges require


global problem solvers. Issues like climate change, pandemics, and economic
disparities demand innovative and collaborative problem-solving efforts from
individuals, organizations, and nations.

Technological Advancements: The rapid advancement of technology owes much to


problem solving. Computer scientists, engineers, and programmers constantly solve
intricate problems to create new technologies and improve existing ones.
Technological innovations have transformed nearly every aspect of modern life.

Problem Solving Strategies


Effective problem solving involves a systematic and structured approach to finding
solutions to challenges, puzzles, or complex issues. Here are several problem-solving
strategies that can help you tackle problems more efficiently and creatively:

1. Understand the Problem


Before jumping into solving a problem, take the time to thoroughly understand it.
Define the problem statement, identify the constraints, and clarify what the desired
outcome or solution should look like. This step is crucial because a well-defined
problem is a problem half solved.

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.

2. Divide and Conquer


Break down complex problems into smaller, more manageable sub-problems.
Address each sub-problem individually, and then integrate the solutions to form a

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.

4. Trial and Error


Sometimes, the most straightforward approach is to experiment and learn through
trial and error. Start with a potential solution, test it, and adjust based on the results.
This method is particularly useful for hands-on or practical problems.

Example: You are solving a jigsaw puzzle. You try different pieces in various positions
until you find the one that fits correctly.

5. Look for Patterns


Patterns often exist within problems and can guide you toward a solution. Analyze the
data or information available to identify recurring elements or trends that could offer
insights or solutions.

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.

Example: Think of programming languages as different types of vehicles. Just as you


choose a car, bicycle, or motorcycle depending on your needs and preferences, you

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.

7. Use Visual Tools


Visual aids, such as graphs, diagrams, and mind maps, can help you visualize the
problem and its components. Flowcharts, in particular, are useful for illustrating the
flow of a process or algorithm.

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.

9. Prioritize and Plan


Once you have multiple potential solutions, prioritize them based on feasibility,
impact, and other relevant criteria. Create a plan that outlines the steps needed to
implement your chosen solution.

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.

10. Seek Feedback


Don't hesitate to seek feedback from peers, mentors, or subject matter experts. They
can provide valuable perspectives, spot potential flaws in your approach, and suggest
alternative solutions.

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.

11. Persist and Iterate


Problem solving can be a challenging and iterative process. Be persistent, and don't
be discouraged by setbacks or failures. Learn from your experiences, adjust your
approach, and continue working toward a solution.

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.

12. Use Algorithms

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.

14. Cross-disciplinary Thinking


Explore solutions and ideas from other fields or disciplines. Sometimes, a solution
from an unrelated domain can be adapted to solve a problem in a novel way.

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.

15. Ethical Considerations


Always consider the ethical implications of your solutions. Ensure that your chosen
approach aligns with ethical standards and doesn't harm individuals or communities.

Example: You're part of a student team working on a computer science project


involving software development. You discuss ethical considerations, ensuring the
computer/software ethic throughout the programming.

16. Reflect and Learn


After solving a problem, take the time to reflect on the process. What worked well,
and what could be improved? Learning from your problem-solving experiences
enhances your skills over time.

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.

Skills required in problem solving

Problem-solving is a complex skill. It involves critical thinking, decision-making,


creativity, and information processing. Effective problem-solvers use a systematic
approach that allows them to break down difficult problems into smaller, more
manageable parts. The be a good problem solver, the following skills are required.

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

Problem Solving Techniques


1. Trial and Error
2. Divide and Conquer
3. Top-down Approach
4. Bottom-up Approach: Working Backwards
5. Analogies
6. Prototyping

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

Algorithms are fundamental to computing and problem-solving in general. They are


step-by-step procedures for solving problems and performing tasks. A good
algorithm possesses several important properties:

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.

Steps involved in Algorithm Development

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.

Step3: Identify the processing operations: All the calculations to be performed in


order to lead to output from the input are to be identified in an orderly manner.

Step4: Processing Definiteness: The instructions composing the algorithm must be


clear and there should not be any ambiguity in them.

Step5: Processing Finiteness: If we go through the algorithm, then for all cases, the
algorithm should terminate after a finite number of steps.

Step6: Possessing Effectiveness: The instructions in the algorithm must be


sufficiently basic and in practice they can be carried out easily.

Implementation Strategies of Algorithms


Algorithms can be designed or implemented or expressed in different ways. This
include;

10
1. Pseudocode
2. Flowchart
3. Program

Pseudocode: Pseudocode is a detailed yet readable description of what an algorithm


should do. It is written in a formal yet readable style that uses a natural syntax and
formatting so it can be easily understood by programmers and others involved in the
development process.

Pseudocode is a high-level, human-readable representation of an algorithm or a


program's logic. It serves as an intermediate step between designing an algorithm
and writing the actual code in a programming language. Pseudocode is used to outline
the structure and steps of an algorithm in a way that is easy to understand, without
getting bogged down in the specific syntax of a programming language.
Pseudocode, by nature, exists in various forms; although most borrow syntax from
popular programming languages (like C, Lisp, or FORTRAN). Natural language is
used whenever details are unimportant or distracting.

Advantages of Pseudocode
Pseudocode offers several advantages in the software development process:

• Clarity and Readability: Pseudocode uses plain language and a simplified


structure that makes it easy to understand for both technical and non-technical
stakeholders. This clarity enhances communication among team members,
stakeholders, and collaborators.
• Language Independence: Pseudocode is not tied to a specific programming
language, making it platform-independent. This allows developers to focus on
algorithmic logic without being constrained by language-specific syntax or
semantics.
• Algorithm Exploration: Pseudocode enables developers to explore and plan
algorithms quickly and easily. It encourages thinking through the logical steps
and flow of an algorithm before diving into coding.
• Facilitates Collaboration: Pseudocode serves as a common ground for team
collaboration. It allows team members with different programming language
expertise to contribute to algorithm design and problem-solving discussions.
• Simplified Abstraction: Pseudocode abstracts the low-level details of
programming languages, reducing cognitive load during algorithm design.
Developers can concentrate on the high-level logic and decision-making
processes.
• Documentation: Pseudocode can be used as documentation for algorithms,
serving as a reference for future development or maintenance. It provides a
clear, high-level overview of the algorithm's structure and steps.

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.

Example: Write a pseudocode to perform the basic arithmetic


operations.

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

Flowcharts: Flowcharts are graphical representations of algorithms and processes.


They use symbols to represent actions, decisions, inputs, outputs, and the flow of
control in a program. Flowcharts help programmers visualize and plan the logical
flow of a program before coding. They are particularly useful for understanding
complex algorithms and for communication between team members.

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:

• Clarity and Visualization: Flowcharts provide a visual representation of


complex processes, making them easier to understand. They help
stakeholders, including non-technical individuals, grasp the logic and flow of a
process quickly.
• Effective Communication: Flowcharts serve as a universal language that can be
easily understood by different team members, including developers,
designers, managers, and clients. They facilitate clear communication and
eliminate ambiguity.
• Simplified Documentation: Flowcharts act as documentation tools for
processes, procedures, and algorithms. They offer a concise and structured
way to document complex systems, making it easier to reference and share
information.
• Problem Identification: Flowcharts can highlight bottlenecks, inefficiencies, or
errors in a process. This makes them valuable for process analysis and
troubleshooting. Identifying issues early can lead to process improvements.
• Process Improvement: Flowcharts are instrumental in process improvement
initiatives such as Lean, Six Sigma, and Total Quality Management (TQM). They
help identify areas for optimization and streamlining.
• Planning and Design: Flowcharts are useful in the planning and design phases
of projects. They allow teams to outline processes and workflows before
implementation, reducing the risk of errors and misunderstandings.
• Standardization: Flowcharts can help standardize procedures and workflows
within an organization. They provide a visual reference that ensures
consistency in how tasks are performed.
• Training and Education: Flowcharts are valuable teaching tools for training new
employees or students. They simplify the explanation of complex processes
and help individuals understand the steps involved.
• Decision Making: Flowcharts can include decision points and conditional
statements, making them helpful in decision-making processes. They visualize
the various options and outcomes, aiding in informed choices.
• Cross-Functional Collaboration: Flowcharts facilitate collaboration between
different departments and teams within an organization. They provide a shared
understanding of processes and workflows.
• Quality Assurance: Flowcharts can be used to define quality control measures
within a process. By visualizing checkpoints and inspections, they help ensure
product or service quality.

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.

Symbols used in Flowcharting


The symbols that we make use while drawing flowcharts as given below are as per
conventions followed by International Standard Organization (ISO).

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.

Off-page connectors: This connector represents a break in the path of flowchart


which is too large to fit on a single page. It is similar to on-page connector. The
connector symbol marks where the algorithm ends on the first page and where it
continues on the second.

Simple Problems using Flowchart


Exercise3:
Draw the Flowchart for both the problems and exercises given above

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.

Program: Another way of expressing algorithm is by a program. A program is in the


real sense, an algorithm expressed or implemented in a particular programming
language.

Let us bring the three ways to express an algorithm together with an example.

Example 1:

Write an algorithm that compute the average of three numbers.

We will implement this algorithm in the three forms of algorithms;

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:

Step1: Start Program


Step2: Read X, Y, Z.
Step3: If X > Y continue
Step4: If Y>Z then print “Y is the largest “and continue
Step5: Continue step 6. Step 5: If X>Z then print “X is the largest
“and continue step 7.
Step6: Print “Z is largest”.

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

In computer programming, a control structure is a fundamental concept that


determines the order in which statements or instructions are executed in a program.
Control structures allow you to control the flow of your program, making it possible
to perform different actions based on conditions, repeat actions multiple times, and
create more complex logic.

There are three fundamental structures that are used for the algorithmic resolution of
problems:

Sequence control structure: This refers to the line-by-line execution by which


statements are executed sequentially, in the same order in which they appear in the
program. They might, for example, carry out a series of read or write operations,
arithmetic operations, or assignments to variables.

Step 1: Read amount,


Step 2: Read years,
Step 3: Read rate,
Step 4: Calculate the interest with formula; Interest =
Amount*Years*Rate / 100
Step 5: Print interest

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.

This section discusses one-way and two-way selections.

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).

The following is an example that shows how an if statement works.

if (score >= 90)

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

In the previous section, you learned how to implement one-way selections in a


program. There are many situations in which you must choose between two
alternatives. For example, if a part-time employee works overtime, the paycheck is
calculated using the overtime payment formula; otherwise, the paycheck is calculated
using the regular formula. This is an example of two-way selection. To choose
between two alternatives—that is, to implement two-way selections—Many languages
provide the if...else statement.

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 (hours > 40.0) //Line 1


wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 2
else //Line 3
wages = hours * rate; //Line 4

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.

Looping/Repetition Structure: Sometimes it is necessary to repeat a set of


statements several times. One way to do this is to type the set of statements in the
program over and over. For example, if you want to repeat a set of statements 100
times, you type the set of statements 100 times in the program. However, this way of
repeating a set of statements is impractical, if not impossible. Fortunately, there is a
simpler approach. Most languages provide statements like while, do..while, do..
until and for to handle repetition, or looping structures that allow you to repeat a set
of statements until certain conditions are met. These looping structures are divided
into the pre-test, post-test, and counted loops.

The Pre-Test Loop


Condition is tested PRIOR to the execution of the statement block
• If the condition is TRUE:
– Perform the statement block (perform one iteration)
– Go back to the condition (to check again)
• If the condition is FALSE:
– “exit” from the loop (do not perform any more iteration)
• The loop may potentially not be executed:
– if condition fails on first test

The while loop is an example of the pre-test loop and has the general form:

while (logical expression)


statement

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:

Everyday, a weather station receives 15 temperatures expressed


in Fahrenheit. A program is to be written which will accept each
Fahrenheit temperature, convert it to Celsius and display the
converted temperature to the screen. After 15 temperatures have
been processed, the words ‘All temperatures processed’ are to be
displayed on the screen. The formula for the conversion is given
below.

Celsius = (Fahrenheit – 32) x 5/9

Write an algorithm for the above problem.

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

The Post-Test Loop


The condition is tested at the END of each iteration of the loop
– At least one iteration will be performed
• If the condition evaluates to TRUE, another iteration will be executed
• If the condition is FALSE, exit from the loop
• Expressed by:
– DO … WHILE loops (for algorithms)
– DO … WHILE (For most languages e.g C, C++, and Java)
The figure below shows the flow of execution of a post-test (DO..WHILE) loop.

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 person invests N1000.00 in a savings account yielding 5


percent interest. Assuming that all interest is left on
deposit in the account, calculate and print the amount of
money in the account at the end of each year for 10 years.
Use the following formula for determining these amounts:

a = p(1+r)n

p is the original amount invested (i.e., the


principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the nth year

• Write an algorithm using any of the looping structure for


the program to calculate the amounts.

Algorithms for some problems

Write an algorithm for the following:

1. Write down an algorithm to find the largest data value of a


set of given data values.

Algorithm largest of all data values:

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

2. Write an algorithm which will test whether a given integer


value is prime or not.

Algorithm prime testing:


Step 1: M = 2
Step 2: read N
Step 3: MAX = SQRT (N)
Step 4: While M < = MAX do
4.1 if (M* (N/M) = N)
4.1.1 then
4.1.1.1 go to step 7
4.2. M = M + 1
Step 5: Write “number is prime”
Step 6: go to step 8
Step 7: Write “number is not a prime”
Step 8: end

3. Write algorithm to find the factorial of a given number N

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.

Algorithm Compute Sum

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

You might also like