Module 1 CS104 Data Structures and Algorithms
Module 1 CS104 Data Structures and Algorithms
MODULE 1
ALGORITHMIC PROBLEM SOLVING AND
RECURSION
UNIT 2. RECURSION……………………………………………………………………………13
Introduction……………………………………………………………………………….13
Objectives…………………………………………………………………………….…..13
Learning Activities……………………………………………………………………….13
Activity 1 - Recursive Algorithm………………………………………………………..13
UNIT SUMMARY………………………………………………………………………..16
Unit Assessment…………………………………………………………………………16
Unit Readings and Other Resources………………………………………………….16
Answers……………………………………………………………………………….….17
2
UNIT 1
ALGORITHMIC PROBLEM SOLVING
INTRODUCTION
This unit introduces learners to data structures and algorithm course. The unit is on the
different data structures and their algorithms that can help implement the different data structures in
the computer. The application of the different data structures is presented by using examples of
algorithms and which are not confined to a particular computer programming language.
OBJECTIVES
Upon completion of this unit the learner should be able to:
1. Describe an algorithm
2. Explain the relationship between data and algorithm
3. Outline the characteristics of algorithms
4. Apply pseudo codes and flowcharts to represent algorithms
KEY TERMS
Data: the structural representation of logical relationships between elements of data
Algorithm: finite sequence of steps for accomplishing some computational task
LEARNING ACTIVITIES
ACTIVITY 1 - INTRODUCTION TO ALGORITHMS AND PROBLEM SOLVING
Introduction
In this learning activity section, the learner will be introduced to algorithms and how to
write algorithms to solve tasks faced by learners or everyday problems. Examples of the
algorithm are also provided with a specific application to everyday problems that the learner is
familiar with. The learners will particularly learn what is an algorithm, the process of developing
a solution for a given task, and finally examples of application of the algorithms are given
3
Algorithm
An algorithm is a finite sequence of steps for accomplishing some computational task. it
must
• Have steps that are simple and definite enough to be done by a computer, and
• Terminate after finitely many steps.
Different algorithms may complete the same task with a different set of instructions in
more or less time, space, or effort than others. Algorithms are essential to the way computers
process information, because a computer program is essentially an algorithm that tells the
computer what specific steps to perform (in what specific order) in order to carry out a specified
task Algorithmic problem solving comes in two phases. These includes:
1. derivation of an algorithm that solves the problem, and
2. conversion of the algorithm into code.
It is worth noting that;
1. an algorithm is a sequence of steps, not a program.
2. same algorithm can be used in different programs, or the same algorithm can be
expressed in different languages, because an algorithm is an entity that is abstracted
from implementation details.
An algorithm can be expressed in following ways;
a) human language
b) pseudo code
c) flow chart
Example
Problem: Given a list of positive numbers, return the largest number on the list.
Inputs: A list L of positive numbers. This list must contain at least one number.
Outputs: A number n, which will be the largest number of the list.
4
Algorithm:
Step 1 Set max to 0.
Step 2 For each number x in the list L, compare it to max.
Step 3 If x is larger, set max to x.
Step 4 max is now set to the largest number in the list.
Conclusion
The learner was introduced to the concept of algorithm and the various ways he/she can
develop a solution to a task. In particular, the learner was introduced to the definition/s of an
algorithm, the three main ways of developing or expressing an algorithm which are the human
language, Pseudo code and the flow chart. Examples was also given to reinforce the concept of
the algorithm.
Assessment
1. Outline the algorithmic steps that can be used to add two given numbers
2. By using an example, describe how the concept of algorithms can be
well presented to a group of students being introduced to it.
1. Each step of an algorithm must be exact; this means that an algorithm must be
precise and ambiguously described. This eliminates any uncertainty. it can also be
said to the characteristic of precision, i.e. the steps are precisely stated(defined).
2. Algorithm must terminate; since the ultimate aim of an algorithm is to solve a problem,
then it must terminate otherwise there won’t be a solution for the problem. This leads
to the fact that an algorithm must have a finite number of steps in its execution. the
presence of endless (infinite) loops must be avoided
3. An algorithm must be effective; this means that an algorithm must provide the correct
answers at all times
4. An algorithm must be general; this means that an algorithm must solve every instance
of a problem
5
5. Uniqueness: results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
6. Finiteness: the algorithm stops after a finite number of instructions are executed.
7. Output: the algorithm produces output
Conclusion
This section has highlighted the properties of algorithms to the learner who is new to the
concept of data structure and algorithm. It also alerts the learner on what to do to ensure the
expected outcomes can be obtained when the algorithm is implemented in any computer
programming language. This will ensure the learner comes up with very correct and accurate
algorithms for solving any task at hand.
Assessment
The student will learn how to design an algorithm using either a pseudo code or
flowchart. Pseudo code is a mixture of English like statements, some mathematical notations
and a selected keyword from a programming language. It is one of the tools used to design and
develop the solution to a task or problem. Pseudo codes have different ways of representing the
same thing and emphasis is on the clarity and not style.
Pseudo Code
6
Example
In the following example, the pseudo code is on program that can add 2
numbers together then display the result.
Solution
Initialize sum to 0.
Calculate sum = num1 + num2
Display sum
Flow chart
Flowchart is a type of diagram that represents an algorithm, workflow or process. it shows
the steps in the form of boxes of various kinds and their order by connecting them with arrows. The
diagrammatic representation illustrates a solution model to a given problem. Flowcharts can be used
in the analysis, design, documenting or managing a process or program in various fields. They are
also used in designing and documenting complex processes or programs.
1. Start and end symbols. They are represented as circles, ovals or rounded (fillet)
rectangles. They contain the word “Start” or “End”, or another phrase signaling the start
or end of a process, such as “submit inquiry” or “receive product”.
Start End
2. Arrows. They show “flow of control”. For example an arrow coming from one symbol and
ending at another symbol represents that control passes to the symbol the arrow points
to. The line for the arrow can be solid or dashed. The meaning of the arrow with dashed
line may differ from one flowchart to another and can be defined in the legend.
4. Subroutines. They are represented as rectangles with double-struck vertical edges. They are
used to show complex processing steps which may be detailed in a separate flowchart.
7
5. Input/Output. These are represented as a parallelogram.
No
Yes
8. Junction symbol. It’s generally represented with a black blob, showing where multiple
control flows converge in a single exit flow. A junction symbol will have more than one
arrow coming into it, but only one going out.
A B C
8
10. Concurrency symbol. It is normally represented by a double transverse line with any
number of entry and exit arrows. They can be used whenever two or more control flows
must operate simultaneously. The exit flows are activated concurrently when all of the
entry flows have reached the concurrency symbol. A concurrency symbol with a single
entry flow is a fork; one with a single exit flow is a join.
Note: All processes should flow from top to bottom and left to right
EXAMPLE
Problem: Calculate and report the grade-point average for a class
Discussion: The average grade equals the sum of all grades divided by the number of students
Output: Average grade
Input: Student grades
Processing: Find the sum of the grades; count the number of students;
calculate average
PSEUDO CODE
Program: Determine the average grade of a class
Initialize counter and sum to 0
9
FLOW CHART
10
Assessment
1. Give two important differences between the flowchart and the pseudocode
2. Give two examples of selection control structures. Use flowchart
3. Draw the different types of symbols used in the flowchart. Explain the
role of each types.
UNIT SUMMARY
In this unit, you have seen what an algorithm is. Based on this knowledge, you should
now be able to characterize an algorithm by stating its properties. We have explored the
different ways of representing an algorithm such as using human language, pseudo codes and
flow chart. You should now be able to present solutions to problems in form of an algorithm”.
Unit Assessment
The following section will test the learners understanding of this module
Answer the following questions
1. Design an algorithm to add two numbers and display result.
2. Write pseudocode to input the dimensions of a rectangle and print
area and perimeter
3. Give an algorithm to find the maximum number.
Answers
1. An algorithm to add two numbers can be written as below;
Step 1 Initialize sum to 0
Step 2 Get values of A and B
11
2. The pseudocode is:
Read length, width
Calculate area = length * width
Calculate perimeter = 2*(length + width)
Display area and perimeter
3. The algorithm is:
12
UNIT 2
RECURSION
INTRODUCTION
This unit introduces the learner to the processes that repeat themselves in a self-similar
way. The processes can either call themselves directly or indirectly during their execution. The
unit will enable the learner to understand the recursion process and solve problems that are
recursive in nature.
OBJECTIVES
Upon completion of this unit the learner should be able to:
1. develop algorithms for recursive programs
2. implement recursive formulation of a problem
3. explain recursion as a form of iteration
KEY TERMS
Base case. Is a boolean test at which the recursion ceases to “wind up” and starts
to “unwind”.
Recursive step. Is a method call which causes the recursion to “repeat” on each
successive iteration (unless the base case is reached).
LEARNING ACTIVITIES
ACTIVITY 1 - RECURSIVE ALGORITHM
Introduction
The learners are introduced to recursive processes learn how a method calls itself in
order to achieve repetitious behavior. By using recursive algorithms, the learners will be in a
position to solve problems of this nature.
Recursive Algorithm
13
smaller (or simpler) input. Thus, if a problem can be solved by utilizing solutions to smaller
versions of the same problem, and the smaller versions reduce to easily solvable cases, then it
means that one can use a recursive algorithm to solve that problem.
The recursive method comprises the following;
1. A base case where the recursion stops and begins to unwind, and
2. A recursive step where the method calls itself
A point worth noting is that a recursive algorithm is said to wind up until the base case is
reached and then unwinds. During the unwinding process, further statement programs
“pending” may be called.
Example 1
The factorial function “!”.
Its definition is:
Again, notice that the definition of “!” includes both a base case (the definition of 0!) and
a recursive part.
14
Laws of Recursion
Recursive algorithms must obey the following laws;
1. A recursive algorithm must have a base case.
2. A recursive algorithm must change its state and move toward the base case.
3. A recursive algorithm must call itself, recursively
An explanation of the laws is as follows;
First law; -The base case allows the algorithm to stop recursing, i.e a problem small
enough to solve directly.
Second law; - a change of state occurs moving the algorithm towards the base case.
This occurs when a change of state takes place and which is best illustrated when a data
modification happens.
Finally; Third law; - the algorithm must call itself.
Example 2
Find the maximum value in a list of numbers;
The solution to the problem would look like the following
Example 3
Adding numbers in the list;
The solution will be something like
This unit introduced the learner to the recursive algorithms. Examples were used to
teach the learner how to write recursive algorithms that can solve self-repeating functions. The
examples used in the teaching of recursion are also not hinged on any computing language and
can thus apply across all the languages. Finally, the learners were introduced to the laws of
recursion.
Assessment
1. List the three key features of a recursive algorithm.
2. Write an algorithm that can multiply two numbers using recursion
UNIT SUMMARY
In this unit, recursion was introduced. you should now be in a position to describe
recursion and where it can be applied. The laws that a recursive algorithm must obey were also
introduced as well as condition necessary for a process to be said to have recursive. Examples
accompanied these explanations were provided where necessary.
Unit Assessment
Check your understanding!
Class exercise
Instructions
Answer the following questions on recursion
1. Write an algorithm for finding the k-th even natural number
2. Explain how a recursive algorithm works
16
Answers
1. The algorithm is:
function even_num(positive integer k):
Input: k , a natural number
Output: k-th even natural number (the first even being 0)
if k = 1, then return 0;
else return (even_num(k-1) + 2);
2. The result of one recursion is the input for the next recursion. The repletion is in the self-
similar fashion. The algorithm calls itself with smaller input values and obtains the results
by simply performing the operations on these smaller values. Generation of factorial,
Fibonacci number series are the examples of recursive algorithms
17