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

Algorithms

Uploaded by

shobasivam85
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Algorithms

Uploaded by

shobasivam85
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT – I

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.

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.
Iterative Control Structure
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.
Advantages of flowcharts
The symbols used in a flowchart are self-explanatory. This makes a
flowchart easier to understand.
Being a graphical representation, flowcharts better communicate the
problem solving logic to the users.
With the help of a flowchart, a problem can be analysed in an effective
way.
It also helps in monitoring, data collection and identifies areas for
improvement or increase in efficiency.
Limitations of flowchart
In case of large programs, the flowcharts may continue too many pages.
This makes them difficult to understand.
It takes a lot of time to represent a program diagrammatically. Any
changes or modification in a flowchart usually requires redrawing the
entire flowchart. It is a challenging job.
Difference between Algorithm, Flowchart, and Pseudocode
ALGORITHMIC PROBLEM SOLVING
Every problem’s solution starts with a plan and that plan is called an
algorithm. So, an algorithm is a plan for solving a problem.
Problem Solving is the process of identifying a problem, developing an
algorithm for identified problem and finally implementing algorithm to
develop a computer program.
The development of an algorithm is the key step in algorithmic problem
solving. Once an algorithm is developed, it can be translated into a
computer program in some programming language.
The algorithmic problem solving process consists of five major steps.
o 1.Obtain a description of the problem.
o 2.Analyze the problem.
o 3.Develop a high-level algorithm.
o 4.Refine the algorithm by adding more details.
o 5.Review the algorithm.
Step 1: Obtain a description of the problem
To solve a problem first we must state problem clearly and precisely.
The algorithmic problem solving process starts by obtaining a description
of the problem. This step is much more difficult than it appears. In the
software development process, the word ‘client’ refers to a person who
wants to find a solution to a problem, and the word ‘developer’ refers to a
person who finds a way to solve the problem. The developer must create an
algorithm that will solve the client's problem. The client is responsible for
creating a description of the problem, but this is often the weakest part of
the process. A problem description suffers from one or more of the
following types of defects:
o the description may rely on unstated assumptions
o the description may be ambiguous
o the description maybe incomplete
o the description may have internal contradictions
These defects are due to carelessness by the client. Part of the developer’s
responsibility is to identify, the defects in the description of a problem,
and to work with the client to rectify those defects.
Step 2: Analyze the problem
The purpose of this step is to determine both the starting and the ending
points for solving the problem.
By analysing a problem we would able to figure out what are the inputs
that our program should accept and the outputs that it should produce.
Asking the following questions often helps to determine the starting
point.
o What data are available?
o Where is that data from?
o What are the rules exist for working with the data?
o What are the relationships exist among the data values?
When determining the ending point, algorithm need to describe the
characteristics of a solution. Asking the following questions often helps
to determine the ending point.
o What new facts will we have?
o What items would have changed?
o What changes would have been made to those items?
o What things will no longer exist?
Step 3: Develop a high-level algorithm
An algorithm is a plan for solving a problem, but plans come in several
levels of detail.
It is better to start with a high-level algorithm that includes the major part
of a solution, but leaves the details until later.
Step 4: Refine the algorithm by adding more detail
A high-level algorithm shows the major steps that need to be followed to
solve a problem. Our goal is to develop algorithms that will lead to
computer programs.
Consider the capabilities of the computer and provide enough details so
that someone else could use the algorithm to write the computer program.
For larger, more complex problems, it is common to go through this
process several times. Each time, more details are added to the previous
algorithm, for further refinement.
This technique of gradually working from a high-level to a detailed
algorithm is often called stepwise refinement.
Stepwise refinement is a process of developing a detailed algorithm by
gradually adding details to a high-level algorithm.

Step 5: Review the algorithm


The final step is to review the algorithm. First, work through the
algorithm step by step to determine whether or not, it will solve the
original problem.
Asking these questions and seeking their answers is a good way to
develop skills that can be applied to the next problem.
o Does this algorithm solve a very specific problem or does it solve a
more general problem?
o If it solves a very specific problem, should it be generalized?
Once an algorithm is developed, translate it into a computer program in
some programming language.
SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS
Iteration
Iteration is a process of repeating the same set of statements again and
again until the specified condition holds true. Humans find iterative tasks
boring but computers are very good at performing iterative tasks.
Computers execute the same set of statements again and again by putting
them in a loop.
In general, loops are classified as:
1.Counter-controlled loops
2.Sentinel-controlled loops
Counter-Controlled Loops
Counter-controlled looping is a form of looping in which the number of
iterations to be performed is known in advance.
Counter-controlled loops are so named because they use a control
variable, known as the loop counter, to keep a track of loop iterations.
The counter-controlled loop starts with the initial value of the loop
counter and terminates when the final value of the loop counter is
reached.
Since the counter-controlled loops iterate a fixed number of times, which
is known in advance, they are also known as definite repetition loops.
Example: Consider a program segment to find the sum of first 100 integers.
i= 1
sum = 0
while (i<= 100):
sum = sum + i
i= i+ 1

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

You might also like