Algorithms
Algorithms
ALGORITHMS
Algorithm is an ordered sequence of finite, well defined, unambiguous
instructions for completing a task.
It is a step-by-step procedure for solving any problem.
Algorithm is an English-like representation of the logic which is used
to solve the problem.
To accomplish a particular task, different algorithms can be written.
They differ by their time and space.
The algorithm is independent of any programming language.
Guidelines for writing Algorithms:
An algorithm should be clear, precise and well defined. It should
always begin with the word ‘Start’ and end with the word ‘Stop’.
Each step should be written in a separate line.
Steps should be numbered as Step 1, Step 2, and so on.
Example: Algorithms to find the greatest among three numbers
Step 1:Start.
Step 2:Read the three numbers A, B, C.
Step 3:Compare A and B. If A is the greatest perform step 4
else perform step 5.
Step 4:Compare A and C. If A is the greatest, output “A is
the greatest” else output “C is the greatest”.
Step 5:Compare B and C. If B is the greatest, output “B is
the greatest” else output “C is the greatest”.
Step 6:Stop.
Properties of an Algorithm:
Finiteness: An algorithm must be terminated after a finite number
of steps.
Definiteness: Each step of an algorithm must be precisely defined.
Input: The data must be present before any operations can be
performed on it. The initial data is supplied by a READ instruction. A
variable can be given initial value using the SET instruction. Example:
READ A, B
SET N=0
Output: After executing all the steps of the algorithm at least one
output must be obtained. The WRITE statement is used to print
messages and variables.
Effectiveness: The operations to be performed in the algorithm can
be carried out manually in finite intervals of time.
Advantages of Algorithm:
It is a simple to understand step by step solution of the problem.
It is easy to debug.
It is independent of programming languages.
It is compatible to computers, because each step of an algorithm can be
easily coded into its equivalent high level language.
BUILDING BLOCKS OF ALGORITHMS
The building blocks are,
o Statements
o State
o Control flow and
o Functions
Statements / Instructions:
An instructions describes an action.
The algorithm consists of finite number of statements.The statements
must be in an ordered form.
The time taken to execute all the statements of the algorithm should be
finite and within a reasonable limit.
Example:
o Read the value of ‘a’ //This is input statement
o Calculate c=a+b //This is assignment statement
o Print the value of c // This is output statement
o Comment statements are given after // symbol, which is used to tell
the purpose of the line.
State:
In an algorithm the state of process can be represented by set of variables.
The state at any point of execution is simply the values of the variables at
that point
As the values of variables are changed, the state changes.
State is a basic and important abstraction. An algorithm starts from the
initial state with some input values and actions are performed ,its state
changes.
During execution of the instruction the state will be stored in one or more
data structure.
Control flow:
The logic of a program may not always be executed in a particular order.
The execution of statements is based on a decision.
The basic control flows needed for writing good and efficient algorithms
are,
o Sequence Control Flow
o Selection Control Flow
o Iteration (Looping) Control Flow
These control flows allow the program to make choices, change direction
or repeat actions.
Sequence Control Flow
In sequence control flow, the instructions are executed one after another
in same order. The instructions in sequence control flow are executed
exactly once.
Example: Algorithm to find the sum of two numbers.
o Step 1: Start
o Step 2: Read two numbers A and B
o Step 3: Calculate sum = A + B
o Step 4: Print the sum value
o Step 5: Stop.
This algorithm performs the steps in a purely sequential order.
Selection Control Flow
In a selection control flow, a condition is tested, and if the condition is
true , one statement is executed; if the condition is false, an alternative
statement is executed.
Example: Algorithm to find the greatest among three
numbers. o Step 1:Start.
o Step 2:Read the three numbers A, B, C.
o Step 3: Compare A and B. If A is the greatest perform step 4
else perform step 5.
o Step 4:Compare A and C. If A is the greatest, print “A is
the greatest”else print “C is the greatest”.
o Step 5:Compare B and C. If B is the greatest, print “B is the
greatest” else print “C is the greatest”.
o Step 6:Stop.
Iteration (Looping) Control Flow
In iterative control flow, a set of statements are repeatedly executed based
on condition. i.e.) if condition is true, set of statements is executed again
and again, until condition becomes false.
Example: Algorithm to find the sum of first 100 integers.
1. Start
2. Assign sum = 0, i= 0.
3. Calculate i= i+ 1 and sum = sum + i
4. Check whether i>= 100, if no repeat step 3. Otherwise go
to next step.
5. Print the value of sum
6. Stop
Functions
Any complex problem will become simpler if the problem is broken
smaller and the smaller problems are solved. The functions are solutions
to smaller problems. These can be used to solve bigger, complex
problems.
During algorithm design the complex problems are divided into
smaller and simpler tasks. These tasks are solved independently by
functions.
A function is a block of organized, reusable code that is used to
perform a similar task of some kind.
It avoids the repetition of some codes over and over. It means the
programmer need not have to write same instructions for a number of
times, to perform the same action.
Functions help easy debugging, testing and understanding of the
program.
Functions reduce program size and the program development time.
Functions provide better modularity and high degree of reusability for the
problems.
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2:Call the function add()
Step 3: Stop
sub function add()
Step1:Function start
Step2:Get a , b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
NOTATIONS
A notation is a system of characters, expressions, graphics or symbols
used in problem solving process to represent technical facts to facilitate the
best result for a problem.
Example: Pseudocode, Flowchart.
Pseudocode
Pseudocode is a short, readable and formally styled English language
used for explaining an algorithm.
Pseudocode does not include details like variable declarations,
subroutines etc. It is a short hand way of describing a computer program.
Using Pseudocode, it is easier for a programmer or
a non-programmer to understand the general working of the program,
because it is not based on any programming language.
It is used to give a sketch of the structure of the program, before the
actual coding. It is not machine readable.
Pseudocode cannot be complied or executed. There is no
standard syntax for Pseudocode.
Preparing a Pseudocode
Pseudocode is written using structured English.
The programmers may use their own style for writing the Pseudocode,
which can be easily understood. It never use the syntax of any
programming language.
Pseudocode uses some keywords to denote programming process. Some
of them are as follows.
Input : INPUT, GET, READ and PROMPT
Output : OUTPUT, PRINT, DISPLAY and SHOW Processing
: COMPUTE, CALCULATE, DETERMINE, ADD,
SUBTRACT, MULTIPLY and DIVIDE
Initialize : SET and INITIALISE
Incrementing : INCREMENT
The Keywords should be capitalized.
There are three control structures used in Pseudocode. They are,
a. Sequence control structure
b. Selection control structure and
c. Iteration control structure
Sequence Control Structures
In sequence control flow, the instructions are executed one after another
in same order. The instructions in sequence control flow are executed
exactly once
EXAMPLE: Find product of any two numbers
READ values of A and B
COMPUTE C by multiplying A with B
PRINT the result C
STOP
Selection Control Structure
In a selection control flow, a condition is tested, and if the condition is
true , one statement is executed; if the condition is false, an alternative
statement is executed.
There are two main selection structures: They are,
1. IF-THEN-ELSE statement
2. CASE statement
The IF-THEN-ELSE statement
In IF-THEN-ELSE selection structure, if the condition is true, the THEN
part is executed. Otherwise the ELSE part is executed.
IF condition THEN
Process1
ELSE
Process2
ENDIF
EXAMPLE: Find maximum of any three numbers
READ values of A, B, C
IF A is greater than B THEN
ASSIGN A to MAX
ELSE
ASSIGN B to MAX
IF MAX is greater than C THEN
PRINT MAX is greatest
ELSE
PRINT C is greatest
STOP
The case statement
The case statement is used when many number of conditions to be
checked. In a case statement, depending on the expression, one of the
conditions is true. Based on the value, the corresponding statements are
executed. If no match for the expression occurs, then the default option is
executed.
CASE value1:
Process1
CASE value2:
Process2
CASE value n:
Process n
END CASE
Iterative Control Structures
In iterative control flow, a set of statements are repeatedly executed based
on condition. i.e.) if condition is true, set of statements is executed again
and again, until condition becomes false. There are two iterative control
structures. They are, WHILE and DO-WHILE.
In WHILE loop, the condition is executed at the beginning of the loop. If
the condition is false then the loop will not be executed.
WHILE condition DO
Statements Statements
END WHILE WHILE condition
END DO
EXAMPLE: Find sum of first 100 integers
INITIALIZE sum to zero
INITIALIZE i to zero
DO WHILE (i less than 100)
INCREMENT i by 1
ADD i to SUM and store in SUM
END DO
PRINT SUM
STOP
Advantages of Pseudocode
A Pseudocode is closer to the programming code. Thus it can be easily
converted into the actual program.
Writing Pseudocode is much easier in comparison with drawing a
flowchart.
Limitations of Pseudocode
It is difficult to understand and manipulate Pseudocode as compared
to algorithm and flowchart.
As there are no specific standards for writing Pseudocode, it becomes
hard to maintain consistency.
Flowchart
A flowchart is a diagrammatic representation of the logic for solving a
task.
A flowchart is drawn using boxes of different shapes with lines
connecting them to show the flow of control.
The purpose of drawing a flowchart is to make the logic of the program
clearer in a visual form.
Flowchart Symbols
Guidelines for preparing a flowchart
There can be only one start and one stop symbol in a flowchart.
Only one flow line can be used with the start and stop symbol.
Direction of flow of information in a flowchart must be from top to
bottom or from left to right. Relevant symbols must be used while
drawing a flowchart.
Only one flow line should come out from a process symbol. If the
flowchart becomes complex, it is better to use connector symbols to reduce
the number of flow lines.
The flow lines should not cross each other.
Ensure that the flowchart has a logical start and finish.
It is useful to test the validity of the flowchart by passing through it with
a simple test data.
Sequence Control Structure
In sequence control structure, the steps are executed in one after another
in same order as they are written.
Sentinel-Controlled Loops
In sentinel-controlled looping, the number of times the iteration is to be
performed is not known before hand.
The execution or termination of the loop depends upon a special value
called the sentinel value.
If the sentinel value is true, the loop body will be executed, otherwise it
will not.
Since the number of times a loop will iterate is not known in advance,
this type of loop is also known as indefinite repetition loop.
Algorithm: To find the sum of first N integers
1.Start
2.Read N
3.Assign sum = 0, i= 0
4.Calculate i= i+ 1 and sum = sum + i
5.Check whether i>= N, if no repeat step 4. Otherwise go to next
step. 6.Print the value of sum
7.Stop
Recursion
Recursion is a powerful programming technique that can be used to solve
the problems that can be expressed in terms of similar problems of
smaller size.
For example, consider a problems to find the factorial of a number n. The
problem of finding the factorial of n can be expressed in terms of a
similar problem of smaller size as n! = n *(n-1)!. Recursion provides an
elegant way of solving such problems.
In recursive programming, a function calls itself. A function that calls
itself is known as a recursive function, and the phenomenon is known as
recursion.
Recursion is classified according to the following criteria: 1.
Whether the function calls itself directly (i.e. direct recursion) or
indirectly (i.e. indirect recursion).
2. Whether there is any pending operation on return from a recursive call.
If the recursive call is the last operation of a function, the recursion is
known as tail recursion.
A Function is directly recursive if it calls itself, i.e. the function body
contains an explicit call to itself.
Indirect recursion occurs when a function calls another function, which in
turn calls another function, eventually resulting in the original function
being called again.
Example: Recursive algorithm for finding the factorial of a number
Step 1: Start
Step 2: Read number n
Step 3: Call factorial (n)
Step 4: Print factorial f
Step 5: Stop
Factorial (n)
Step 1: if n = = 1 then return 1
Step 2: Else
f = n*factorial (n-1)
Step 3: Return f