You are on page 1of 21

Module 2: Algorithm and Features of Algorithms

(Week 1)

2.1 Algorithms and Definitions


Algorithm is a step-by-step procedure, which defines a set of instructions to
be executed in a certain order to get the desired output. Algorithms are
generally created independent of underlying languages, i.e., an algorithm can
be implemented in more than one programming language. From the data
structure point of view, following are some important categories of algorithms:
(a) Search: Algorithm to search an item in a data structure.
(b) Sorting: Algorithm to sort items in a certain order.
(c) Insert: Algorithm to insert item in a data structure.
(d) Update: Algorithm to update an existing item in a data structure.
(e) Delete: Algorithm to delete an existing item from a data structure.

2.2 Why Study Algorithms


Data structures and algorithms (DSA) provides an insight into how efficient it
is to apply different techniques for problem solving and it teaches the science
of evaluating the efficiency of an algorithm. This enables programmers to
choose the best of various choices. Some of the reasons for studying
algorithms are:

(i) To understand the basic idea of the problem.


(ii) To find an approach to solve the problem.
(iii) It helps to improve problem solving skills.
(iv) To improve the efficiency of existing techniques.
(v) To understand the basic principles of designing the algorithms.
(vi) To compare the performance of the algorithm with respect to other
techniques.
(vii) It is the best method of description without describing the
implementation detail.
(viii) The Algorithm gives a clear description of requirements and goal of
the problem to the designer.
(ix) A good design can produce a good solution.
(x) To understand the flow of the problem.
(xi) To measure the behaviour (or performance) of the
algorithms/methods in all cases (best cases, worst cases, average
cases)
(xii) With the help of an algorithm, we can also identify the resources
(memory, input-output) cycles required by the algorithm.
(xiii) With the help of algorithm, we convert art into a science.

Page 1 of 21
2.3 Characteristics of a good Algorithm
Some of the desirable characteristics of a well – written algorithms are:
(a) Integrity/Correctness: Integrity refers to the accuracy of a calculations
in an algorithm and is an absolutely necessity in any algorithm. All
algorithms’ enhancements are meaningless if calculations are not
correctly carried out.
(b) Clarity: Clarity refers to the overall readability of an algorithm with
particular emphasis on its underlying logic. If an algorithm is written
clearly, it should be possible for another programmer to follow the
algorithm logic without undue effort.
(c) Simplicity: clarity and accuracy of an algorithm can be enhanced by
making algorithm logic simple and consistent with the overall algorithm
objectives. This can be achieved by sacrificing certain amount of
computation efficiency in order to maintain a relatively simple and
straightforward algorithmic structure.
(d) Efficiency: Efficiency is concern with algorithm execution and efficient
memory utilization. This can be achieved by avoiding unstructured
statements in the algorithm. Efficiency should not be obtained at the
expense of clarity or simplicity.
(e) Modularity: An algorithm is said to be modular if it is decomposed into
a series of identifiable tasks called subalgorithms or procedures. Each of
these subtasks can be implemented as a separate algorithm module. The
use of a modular programming structure enhances the accuracy and
clarity of an algorithm. It also facilitates future algorithms alterations.
(f) Generality: An algorithm should be made to be general as possible,
within reasonable limit. Variables should be used to read in the values
of certain key parameters rather than placing constant (fixed) values into
the program. Considerable amount of generality can be obtained with
very little additional programming effort.
(g) Robustness: Robustness means that how an algorithm can clearly define
our problem.
(h) Maintainability: Here, maintainability means that the algorithm
should be designed in a very simple structured way so that when we
redefine the algorithm, no major change will be done in the algorithm.
(i) Functionality: It considers various logical steps to solve the real-world
problem.
(j) User-friendly: If the algorithm is not user-friendly, then the designer
will not be able to explain it to the programmer.
(k) Extensibility: If any other algorithm designer or programmer wants to
use your algorithm then it should be extensible
(l) Documentation: The programmer must integrate good documentation
in every algorithm, that is, statements that briefly explain what every

Page 2 of 21
part of the algorithm is doing. Documentation (or Comments) makes
algorithms easy to read, understand and modify when necessary.

2.4 Features of a Good Algorithms


Not all procedures can be called an algorithm. An algorithm should have the
following characteristics −
(a) Unambiguous: Algorithm should be clear and unambiguous. Each of
its steps (or phases), and their inputs/outputs should be clear and
must lead to only one meaning.
(b) Input: An algorithm should have 0 or more well-defined inputs.
(c) Output: An algorithm should have 1 or more well-defined outputs, and
should match the desired output.
(d) Finiteness: Algorithms must terminate after a finite number of steps.
(e) Feasibility: Should be feasible with the available resources.
(f) Independent: An algorithm should have step-by-step directions, which
should be independent of any programming code.

2.5 Algorithm Development and Software Development Life Cycles


(SDLC)
The development of an algorithm (a plan) is a key step in solving a problem.
Once we have an algorithm, we can translate it into a computer program in
some programming language. Algorithm development is the act of designing
the steps that solve a particular problem for a computer or any other device
to follow not excluding human being, but in this case computers only and
computer like devices.

The steps in Algorithm development are similar to that of the Software


Development Life Cycle model. Software Development Life Cycle (SDLC) is a
framework that defines the steps involved in the development of software at
each phase. It covers the detailed plan for building, deploying and maintaining
the software. SDLC defines the complete cycle of development (i.e., all the
tasks involved in planning, creating, testing, and deploying a Software
Product). The phases of SDLC methodology are:

• Requirement gathering and Analysis


• Software Analysis
• Software design
• Coding (Building)
• Software Testing
• Implementation (Deployment)
• Maintenance

Page 3 of 21
The process of algorithm development generally involves many steps. The
general steps involved in algorithm development are as follows:
▪ Problem Definition
▪ Problem Analysis
▪ Algorithm Design
▪ Flowchart/Pseudocode
▪ Implementation
▪ Testing
▪ Documentation

(a) Problem Definition


At this step, the problem that the algorithm needs to solve is clearly
defined. It important to clearly understand the problem statement so that
a proper algorithm can be designed. This stage includes understanding the
input data, desired output, and constraints or requirements.

(b) Problem Analysis


In this step, the problem is analyzed so as to gain insights into its
characteristics, complexity, and potential solutions. This may involve
studying the data, identifying patterns, understanding the relationships
between different variables, and considering different approaches.

(c) Algorithm Design


Based on the problem analysis, an algorithm is designed that outlines the
step-by-step process for solving the problem. This may involve selecting
appropriate data structures, choosing suitable problem-solving
techniques, and designing tools for defining the logic or flow of the
algorithm.

(d) Flowchart/Pseudocode Development


A flowchart is a visual representation of the algorithm for non-technical
people so that they can easily understand the algorithm. It is expected at
this step to create a high-level representation of the algorithm using
flowcharts. Flowcharts use graphical symbols to represent the steps and
flow of the algorithm.

(e)Implementation
In this step, the algorithm design is translated into a specific computer
programming language. Write the code to implement the algorithm, taking
into consideration the syntax, data types, and control structures of the
programming language.

(e) Testing

Page 4 of 21
Test the algorithm by giving the test data and see if the desired output is
generated. Testing with various inputs to verify the correctness and
effectiveness of the algorithm. Identify and fix any bugs or errors that may
arise during testing. Testing may involve different types of inputs,
including edge cases, to ensure the algorithm performs correctly in
different scenarios.

(d) Documentation
Document the algorithm, including its design, implementation details, and
any assumptions or limitations. This documentation helps others understand
and use the algorithm effectively.

2.6 Algorithm Approaches


There are two approaches for designing an algorithm which are
▪ Top-Down Approach
▪ Bottom-up approach

2.6.1 Top-Down Approach


Top-Down Approach is an approach to design algorithms in which a bigger
problem is broken down into smaller parts. Thus, it uses the decomposition
approach. This approach is generally used by structured programming
languages such as C, COBOL, FORTRAN. The drawback of using the top-
down approach is that it may have redundancy since every part of the code is
developed separately. Also, there is less interaction and communication
between the modules in this approach. The implementation of algorithm using
top-down approach depends on the programming language and platform.
Top-down approach is generally used with documentation of module and
debugging code.

2.6.2 Bottom-Up Approach


Bottom-Up Approach is one in which the smaller problems are solved, and
then these solved problems are integrated to find the solution to a bigger
problem. Therefore, it uses composition approach. It requires a significant
amount of communication among different modules. It is generally used with
object-oriented programming paradigm such as C++, Java, and Python. Data
encapsulation and data hiding is also implemented in this approach. The
bottom-up approach is generally used in testing of modules.

2.7 Algorithm Design Techniques


An Algorithm design technique (strategy or paradigm) is a general approach
to solving problems algorithmically that is applicable to a variety of problems
from different areas of computing. They are techniques that provides the
construction of efficient solutions to problems and they provide templates

Page 5 of 21
suited to solve a broad range of diverse problems. No matter which
programming language that is been used, it is important to learn algorithm
design techniques in data structures in order to be able to build scalable
systems. Selecting a properly design technique for algorithms is a complex
but important task. Some of the main algorithm design techniques are:
(a) Brute-force or exhaustive search
(b) Divide and Conquer
(c) Greedy Algorithms
(d) Dynamic Programming
(e) Branch and Bound Algorithm
(f) Randomized Algorithm
(g) Backtracking
(h) Linear Programming

2.7.1 Brute-force or exhaustive search


Brute force is a straightforward approach to solve a problem based on the
problem’s statement and definitions of the concepts involved. It is considered
as one of the easiest approaches to apply and is useful for solving small – size
instances of a problem. A brute force algorithm solves a problem through
exhaustion: it goes through all possible choices until a solution is found. For
example, if there is a lock of 4-digit PIN and the digits is to be chosen from 0-
9, then the brute force will be trying all possible combinations one by one like
0001, 0002, 0003, 0004, and so on until we get the right PIN. In the worst
case, it will take 10,000 tries to find the right combination. The time
complexity of a brute force algorithm is often proportional to the input size.
Brute force algorithms are simple and consistent, but very slow. Brute force
is important due to its wide applicability and simplicity. Example of the Brute-
force techniques is the Linear Search, Selection sort, Brute-force string
matching, convex hull problem, Exhaustive search (Traveling salesman,
Knapsack, and Assignment problems).

2.7.2 Divide and Conquer


The Divide and Conquer is a top-down approach. In the divide and conquer
approach, the problem is divided into several small sub-problems. Then the
sub-problems are solved recursively and combined to get the solution of the
original problem.

The divide and conquer approach involve the following steps at each level:
▪ Divide: The original problem is divided into sub-problems.
▪ Conquer: The sub-problems are solved recursively.
▪ Combine: The solutions of the sub-problems are combined together to
get the solution of the original problem.

Page 6 of 21
The divide and conquer approach are applied in algorithms such as Binary
search, Quick sort, Merge sort, Integer multiplication, Matrix inversion,
Matrix multiplication, etc.

2.7.3 Greedy Algorithms


A Greedy algorithm is an algorithmic paradigm that follows the problem-
solving heuristic of making the locally optimal choice at each stage with the
hope of finding a global optimum. In greedy algorithm of optimizing solution,
the best solution is chosen at any moment. A greedy algorithm is very easy to
apply to complex problems. It decides which step will provide the most
accurate solution in the next step. This algorithm is a called greedy because
when the optimal solution to the smaller instance is provided, the algorithm
does not consider the total program as a whole. Once a solution is considered,
the greedy algorithm never considers the same solution again.
A greedy algorithm works recursively creating a group of objects from the
smallest possible component parts. Recursion is a procedure to solve a
problem in which the solution to a specific problem is dependent on the
solution of the smaller instance of that problem.

Greedy method is used to solve the optimization problem. An optimization


problem is a problem in which given a set of input values, which are required
either to be maximized or minimized (known as objective), i.e., some
constraints or conditions.
▪ Greedy Algorithm always makes the choice (greedy criteria) looks best
at the moment, to optimize a given objective.
▪ The greedy algorithm doesn't always guarantee the optimal solution
however it generally produces a solution that is very close in value to
the optimal.

Examples of Greedy algorithms are MST problem: Prim’s algorithm, Kruskal’s


algorithm (Sets and set operations), Dijkstra’s algorithm for single-source
shortest path problem, Huffman tree and code.

2.7.4 Dynamic Programming


Dynamic programming, like the divide-and-conquer method, solves problems
by combining the solutions to sub problems and after solving each sub-
problem, dynamic programming combines all the solutions to get ultimate
solution. A Dynamic-programming algorithm solves each subproblem just
once and then saves its answer in a table, thereby avoiding the work of
recomputing the answer every time it solves each subproblem. Unlike divide
and conquer method, dynamic programming reuses the solution to the sub-
problems many times. Recursive algorithm for Fibonacci Series is an example

Page 7 of 21
of dynamic programming. Matrix-chain Multiplication and Assembly Line
Scheduling are another example.

2.7.5 Branch and Bound Algorithm


A Branch and Bound algorithm are an optimization technique that is used to
get an optimal solution to a problem. It looks for the best solution for a given
problem in the entire space of the solution. A branch and bound algorithm
search the set of all possible solutions before recommending the best one.
This algorithm enumerates possible candidate solutions in a stepwise manner
by exploring all possible set of solutions. The bounds in the function to be
optimized are merged with the value of the latest best solution. It allows the
algorithm to find parts of the solution space completely.

The purpose of a branch and bound search is to maintain the lowest-cost


path to a target. Once a solution is found, it can keep improving the
solution. Branch and bound search are implemented in depth-bounded
search and depth–first search. This technique is very useful in solving
combinatorial optimization problem that have multiple solutions, discrete
and general mathematical optimization problems. Other examples are Job
sequencing and Travelling salesman problem.

2.7.6 Randomized Algorithm


An algorithm that uses random numbers to decide what to do next anywhere
in its logic is called Randomized Algorithm. For example, in Randomized Quick
Sort, we use a random number to pick the next pivot (or we randomly shuffle
the array). Typically, this randomness is used to reduce time complexity or
space complexity in other standard algorithms. Randomized algorithms are
classified based on whether they have time constraints as the random variable
or deterministic values. They are designed in their two common forms − Las
Vegas and Monte Carlo.
▪ Las Vegas: The Las Vegas method of randomized algorithms never gives
incorrect outputs, making the time constraint as the random variable.
For example, in string matching algorithms, Las vegas algorithms start
from the beginning once they encounter an error. This increases the
probability of correctness. e.g., Randomized Quick Sort Algorithm.

▪ Monte Carlo: The Monte Carlo method of randomized algorithms


focuses on finishing the execution within the given time constraint.
Therefore, the running time of this method is deterministic. For
example, in string matching, if monte carlo encounters an error, it
restarts the algorithm from the same point. Thus, saving time. e.g.,
Karger’s Minimum Cut Algorithm

Page 8 of 21
2.7.7 Backtracking
Backtracking is an optimization technique to solve combinational problems.
It is applied to both programmatic and real-life problems. In backtracking, we
start with a possible solution, which satisfies all the required conditions. Then
we move to the next level and if that level does not produce a satisfactory
solution, we return one level back and start with a new option. Backtracking
Algorithm tries each possibility until they find the right one. It is a depth-first
search of the set of possible solution. Eight queen problem, Sudoku puzzle
and going through a maze are popular examples where backtracking
algorithm is used.

2.7.8 Linear Programming


Linear programming describes a wide class of optimization job where both the
optimization criterion and the constraints are linear functions. It is a
technique to get the best outcome like maximum profit, shortest path, or
lowest cost. In this programming, we have a set of variables and we have to
assign absolute values to them to satisfy a set of linear equations and to
maximize or minimize a given linear objective function.

2.8 How to Write an Algorithm


There are no well-defined standards for writing algorithms. Rather, it is
problem and resource dependent. Algorithms are never written to support a
particular programming code. As we know that all programming languages
share basic code constructs like loops (do, for, while), flow-control (if-else),
etc. These common constructs can be used to write an algorithm. We write
algorithms in a step-by-step manner, but it is not always the case. Algorithm
writing is a process and is executed after the problem domain is well-defined.
That is, we should know the problem domain, for which we are designing a
solution. For Example, the problem below designs an algorithm to add two
numbers and display the result.

Step 1 − START
Step 2 − declare three integers a, b & c
Step 3 − define values of a & b
Step 4 − add values of a & b
Step 5 − store output of step 4 to c
Step 6 − print c
Step 7 − STOP

Algorithms tell the programmers how to code the program. Alternatively, the
algorithm can be written as −

Page 9 of 21
Step 1 − START ADD
Step 2 – Read values of a & b
Step 3 −c←a+b
Step 4 − display c
Step 5 − STOP

In design and analysis of algorithms, usually the second method is used to


describe an algorithm. It makes it easy for the analyst to analyze the algorithm
ignoring all unwanted definitions. He can observe what operations are being
used and how the process is flowing.

Writing step numbers, is optional.

We design an algorithm to get a solution of a given problem. A problem can


be solved in more than one way.

2.9 Expressing an Algorithm


An algorithm can be expressed in several different ways including
✓ Structured English,
✓ Pseudocode and
✓ Flowchart, etc.

The most common among three ways of expressing an algorithm are


Pseudocode and Flowchart. These tools are not programming languages and
they cannot be processed by a computer. Their purpose is to provide a way
for a programmer to document his idea in a program design. An Algorithm
expressed using any of the two tools mention above must be converted into a
program using an appropriate programming language before it can be
executed by the computer.

Page 10 of 21
2.10 Algorithm Format Conventions and Design Notations/Tools
The solution process for most problems basically involves making
assignments, comparisons and repeating some predefined simple steps.
Others may include performing some arithmetic operations like addition,
subtraction, multiplication and division. We shall adopt the following
notations for the purpose of designing algorithms.

(a) Identifying Number/Name: Each algorithm is assigned an identifying


number or a name as shown in the algorithm above (i.e. START ADD)
(b) Start, Exit/Stop: To indicate the beginning and end of the Algorithm
(c) Read, Accept or Input: To input or read a variable
(d) Step: This will be used to place the Algorithm statement in each line
and proper indentation will be used to place statement(s) in each step.
(e) Print, Display or Output: The instructions will be used to output the
result of processing.
(f) Variable Names: Variable names are used to represent values that
changes in the course of the algorithm execution. The convention for
variables names is that Variable names should start with a letter and
can be followed by a letter or a digit. The first letter of each word should
be capitalized. In addition, variable name should be descriptive, that is,
it must represent what it represents. For example, a, b and c in the
above algorithm to add two numbers are variable names.
(g) Comments: Comments are explanatory notes that are added to an
Algorithm to improve readability and understanding. It can also explain
what each statement or part of an algorithm is meant to achieve.
Comments are enclosed in angular bracket (i.e. […] ).
(h) Glossary/Program Specification: A short and descriptive word can
be used to represent variables. Note that this is not part of the algorithm
(i) Assignment Symbols: This is represented using an arrow (←) or colon
symbol followed by an equal to (:=). For example,
X←Y means assign the value of variable Y to variable X
A:= B + C means add B to C and assign the result to A

(j) Arithmetic Symbols: Arithmetic symbols will be represented using the


✓ + for addition,
✓ - for subtraction,
✓ / for division,
✓ * for multiplication and
✓ ^ or ** - For exponentiation
✓ Mod for Modulus (Remainder after Division)
✓ Div for Integer division

Page 11 of 21
Examples:
X^2 means X2
X^Y means Xy
X + Y means X plus Y
X/Y means x divided by Y
X – Y means X minus Y
X + Y means X plus Y

(k) Relational symbols: this will be represented as shown below:


< For less than
> For greater than
>= For greater than or equal to
<= For less than or equal to
= For equal to
<> not equal to

For example, X = Y means “Is the value of X equal to the value of Y.

(l) Branching Operations/Selection: This is a situation where a decision


is made to perform one block of instruction or another. A Branch is a
point in a program where the computer will make a decision about
which set of instructions to execute next. The transferring of control or
jump from one part of a program to another part of the same program
is called Branching. Selection is an operation in which one group of
statements is selected from several available groups depending on the
value of our expression. Branching operations are carried out in most
Programming Languages using the following Control Structures:
✓ IF Statements
✓ GOTO Statement
✓ Select case/ Switch Statements

(i) IF Statements occur in three forms which are


✓ Simple or One-way IF statement which has the syntax:
IF (condition) Then Statement
✓ Two – Way IF statement which has the syntax:
IF (condition) Then
Statement – 1
ELSE
Statement – 1
ENDIF
e.g,
IF (a > b) Then
c = 20

Page 12 of 21
else
c = 40
Endif

✓ Multiple or Nested IF statement with the Syntax:


IF (condition-1) Then
Statement – 1
ELSE (condition-2) Then
Statement – 2
ELSE (condition-3) Then
Statement – 2
.
.
.
ELSE (condition-n) Then
Statement – n
ELSE
Statement – else
ENDIF
e.g.
IF (Number = 0) Then
Print Number, “Is Zero”
Else IF (Number < 0) Then
Print Number, “Is Negative”
Else
Print Number, “Positive”
ENDIF

(ii) Goto Statement: The GOTO statement is used to alter the normal
sequence of algorithm (i.e., Pseudocode) execution by transferring
control to some other part of the program. In its general form, the
GOTO statement is written as:
GOTO label
where label is an identifier/step that is used to label the target
statement to which control will be transferred. Control may be
transferred to any other statement within the algorithm. (To be more
precise, control may be transferred anywhere within the current
Algorithm. The target statement must be labeled, and the label must
be followed by a colon. Thus, the target statement will appear as:
label: statement
Each labeled statement within the program (more precisely, within the
current function) must have a unique label; i.e., no two statements can
have the same label. For example

Page 13 of 21
Step 3: Print “ Hello”
.
.
.
GOTO Step 3

(iii) Select Case structure: This statement provides a structured way to


handle multiple branching. Several alternatives are offered but only
one is selected and executed. After the set of instructions are
executed, control transfers to the end of the structure. They are can
be several alternatives and the computer decides which set of
instructions to execute by examining the value of the Case values.
The syntax is:
Select Case (Expression)
When expression-1: Statement-1
When expression-2: Statement-2
.
.
.
When expression-n: Statement-n
Case Else
Statement – else
End Select Case
e.g.
Select Case color
When ‘R’: Print “RED”
When ‘G’: Print “GREEN”
When ‘B’: Print “BLUE”
CASE ELSE
Print “BLACK”
END SELECT

(m) Loop Control Statements: Looping is the repeated execution of


some portion of a program either in a specified number of times or until
a particular condition has been satisfied. Looping operations are carried
out in most Programming Languages using the following Control
Structures:
✓ While Structure
✓ Do While Structure
✓ FOR Structure
✓ For-each Structure
✓ Repeat … Until Structure

Page 14 of 21
For the purpose of algorithm, the third kind of logic refers to either of two
types of structures involving loops. Each type begins with a Repeat statement
and is followed by a module/statements/group of statements called the body
of the loop. For clarity, we will indicate the end of the structure by the
statement
[End of loop]

The repeat-for loop uses an index variable, such as K, to control the loop. The
loop will usually have the form:

Repeat for Loop_variable = start-value to stop_value by step-value


[Module/Statement(s)]
[End of Loop]

Here start-value is called the initial value, stop_value is the end value or test value,
and step-value is the increment. Loop_variable is the variable used to control the
loop.

For example,
Repeat for counter = 1 to 5 by 1
Print Counter
End of Loop

The second is the repeat-while loop and it uses a condition to control the loop.
The loop will usually have the form

Repeat while condition:


[Module/Statements]
[End of loop]

For example,
Repeat while ( i < 10)
counter = counter + 1
Print Counter
End of Loop

2.11 Algorithm vs Pseudocode


An Algorithm and Pseudocode are used interchangeably but in actual fact
they are different. A Pseudocode is one of the ways to express an algorithm.
'Pseudo' means false or imitation and 'code' means program instructions.

An Algorithm is defined as a finite step by step procedure for solving a problem


giving an initial step. It is a detailed specification of the solution to a problem.

Page 15 of 21
A procedure is a finite sequence of well-defined steps or operations used in
solving a problem. An algorithm represents logical structure of a program to
be coded. An important characteristic of a correctly formulated algorithm is
that it guaranteed to accomplish the task for which the algorithm was
designed.

An algorithm for a computer is the set of steps that explains how to begin with
the known information specified in a problem statement and manipulate that
information to arrive at a solution and is typically first written in a format that
is not specific to a particular computer or programming languages. This way,
the software engineer focuses on formulating a correct algorithm rather than
an expressing the algorithm using the commands of a computer programming
language. In the later phase of the software development process, the
algorithm is translated into instructions written in a computer programming
language so that the algorithm can be implemented by a computer.

Pseudocode is a notational system for algorithm that describes the program


logic using mixture of English language, mathematical notations, certain
programming language constructs and control words such as IF ... Then. It
lists in plain English language the sequence of operations necessary to solve
a problem. Pseudocode is a descriptive language use to express an algorithm
and is less formalized and hence the structure and wording are left up to the
programmer or the person writing the algorithm. Pseudo code is self-
explanatory since it is in plain English. It does not require separate
documentation. It uses a structure similar to that of BASIC program.
Sentences are generally written line by line, each line for one sentence, with
proper indentation. For Pseudocode, rules of syntax are not strict. The lines
are properly intended for ease in reading and understanding the sequence of
operations. Iteration constructs (repeat ... until and Do while ... End do
statements), and selection constructs (if .. then .. else and if .. else if ..
statements) are also used in detailing the processing. The purpose is to allow
easy readability and proper documentation. Pseudocode is not language
oriented and uses plain English for detailing the sequence.

2.12 Examples of Algorithms


Some examples of algorithm are given below:
2.12.1 Sequential Execution
Example 1: Design an algorithm to find sum of two numbers and output the
result.

Solution:
Program Specification/Glossary
Fnum = First Number

Page 16 of 21
Snum = Second Number
Sum = Sum of the Numbers

Algorithm
Step 1: START ADD
[Algorithm to Find the Sum of two Numbers]
Step 2: Input Fnum and Snum
Step 3: Sum ← Fnum + Snum
Step 4: Print “Sum = ”, Sum
Step 5: STOP

Example 2:- Construct an Algorithm to compute the weight W of a hollow


sphere of diameter d, wall thickness t, and density ρ, using the following
equations:
R0 = d/2, R1 = d/2 – t
V = 4/3Π(R 1 - R 0), W = ρV
3 3

Solution
Program Specification/Glossary
d – diameter
t – wall thickness
density ρ = rho
Ro – Ro
Ri = Ri
Volume = V
Weight = W

Algorithm
Step 1: START HOLLOWSPHERE
[Algorithm to Compute the Weight of a Hollow Sphere]
Step 2: Read d, t and rho
Step 3: Ro := d/2, Ri = Ro – t
Step 4: V := 4 * 3.142 * (Ri ^3 – Ro ^ 3)/3
Step 5: W:= rho * V
Step 6: Print “Weight = ”, W
Step 7: STOP
Example 3:- Write an Algorithm to convert a temperature reading in degrees
Fahrenheit to degrees Celsius, using the formula C = (5/9 )x (F- 32) .

Solution
Program Specification/Glossary
Temperature in Celsius degrees - Celsius
Temperature in Fahrenheit degrees – Fahrenheit

Page 17 of 21
Algorithm
Step 1: START TEMPERATURECONVERSION
[Algorithm to convert Temperature Reading in degree Fahrenheit
to Celsius]
Step 2: Input Fahrenheit
Step 3: Celsius ← 5/9 * (Fahrenheit – 32)
Step 4: Print “Temperature in degree Celsius = ”, Celsius
Step 5: STOP

Example 4: Write an Algorithm that calculates the Energy (Q) needed to heat
water from an initial temperature to a final temperature. The formula for
computing the Energy is:
Q = M * (final temperature – initial temperature) * 4184
Where M is the weight of water in Kilograms, temperatures are in degrees
Celsius and Energy Q is measured in joules.

Solution
Step 1: START ENERGYNEEDED
[Algorithm to compute in Joules]
Step 2: Read Mass, InitialTemperature, FinalTemperature
Step 3: Energy := Mass * (InitialTemperature – FinalTemperature) * 4184
Step 4: Print “Energy in Joules = ”, Enegry
Step 5: STOP

Example 5: Write an Algorithm to Calculate the Perimeter of a Triangle with


sides a, b and c. (Hints: P = (a + b + c)/2.

Solution
Step 1: START TRIANGLE
[Algorithm to compute the Perimeter of a triangle]
Step 2: Read A, B, and C
Step 3: Perimeter ← (A + B + C)/2
Step 4: Print “Perimeter = ”, Perimeter
Step 5: STOP

2.12.2 Selection/Branching Operations


Example 1: Write an Algorithm to input two numbers and determine which
of them is Larger.
Solution
Step 1: START LARGER
[Algorithm to input two numbers and determine Larger]
Step 2: Input Fnum, Snum
Step 3: IF (Fnum > Snum) Then

Page 18 of 21
Step 4: Print Fnum, “ Is Larger”
Step 5: Else
Step 6: Print Snum, “ Is Larger”
Step 7: ENDIF
Step 8: STOP

Example 2: Write an Algorithm to input a number and determine whether it


is positive, zero or positive.
Solution
Step 1: START DETERMINENUMBER
[Algorithm to input a number and determine whether it is positive, zero
or negative]
Step 1: Read Number
Step 2: IF (Number = 0) Then
Step 3: Print Number, “Is Zero”
Step 4: Else IF (Number < 0) Then
Step 5: Print Number, “Is Negative”
Step 6: Else
Step 7: Print Number, “Is Positive”
Step 8: ENDIF
Step 9: STOP

Example 3: A mathematical relationship is described by:


Y = 4x2 – x2 + 1 if x > = 0
X2 + X – 1 if x < 0
Design an algorithm to illustrate the relationship.

Solution
Step 1: START RELATIONSHIP
[Algorithm to compute mathematical relationship]
Step 2: Input X
Step 3: IF (X > = 0) then
Step 4: Y← 4 *X ^ 2 - X^ 2 + 1
Step 5: Else
Step 6: Y← X ^2 + X – 1
Step 7: ENDIF
Step 8: Print Y
Step 9: STOP

2.12.3 Looping Operations


Example 1: Design an Algorithm to compute the Sum and Average of 50
numbers.

Page 19 of 21
Solution
Program Specification/Algorithm
Number – Numbers to be added
N – No of terms
Sum – Sum of the Numbers
Average – Average of the Numbers

Algorithm
Step 1: START SUMMATION
[Algorithm to compute the Sum and Average of 50 numbers]
Step 2: Sum: = 0.0.
Step 3: Input N
Step 4: Repeat for counter = 1 to N by 1
Step 5: Input Number
Step 6: Sum := Sum + Number
Step 7: End of Loop
Step 8: Average := Sum/N
Step 9: Print Sum
Step 10: Print , Average
Step 11: STOP

Example 2: Design an algorithm to calculate the sum and average of the first
50 integer numbers and outputs the result.
Solution:
Step 1: START SUMMATION
[Algorithm to compute the Sum and Average of the first 50 Integer
numbers]
Step 1: Sum: = 0
Step 2: Input N
Step 3: Repeat for counter = 1 to N by 1
Step 4: Sum := Sum + Counter
Step 5: End of Loop
Step 6: Average:= Sum/N
Step 7: Print Sum
Step 8: Print Average
Ste9 9: STOP

Example 3: Design an algorithm to convert measurement in inches to


centimeters (hint 1 inch = 2.54cm, Starting from 1, increment counter by 0.5
until counter = 5)

Page 20 of 21
Solution
Program specification/Algorithm
Let measurement in inches = inches
Let measurement in centimeters = centimeters.

Algorithm
Step 1: START MEASUREMENT
[Algorithm to convert from Inches to Centimeters]
Step 2: Inches := 1
Step 3: Read n (i.e. No of terms)
Step 4: Repeat for inches = 1 to n by 0.5
Step 5: centimeters: = 2.54 * inches
Step 6: Print inches, centimeters.
Step 7: End Loop
Step 8: STOP

Example 4: Write an Algorithm to compute the factorial of a number (Use


loop – structure). The factorial of a number is calculated as:
1 if n = 0
n!=  
1  2  3...  n if n  0 
Solution
Step 1: Start FACTORIALCOMPUTATION
[Algorithm to compute the Factorial of a Number]
Step 2: Factorial := 1
Step 3: Read Number
Step 4: IF (Number < = 0) Then
Step 5: Factorial := 1
Step 6: Else
Step 7: Repeat for counter = 2 to Number by 1
Step 8 Factorial := Factorial * Counter
Step 9: End Loop
Step 10: Print Number, “! = ”, Factorial
Step 11: STOP

Page 21 of 21

You might also like