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

UNIT I (1)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

UNIT I (1)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT I

ALGORITHMIC PROBLEM SOLVING

Algorithms, building blocks of algorithms (statements, state, control flow, functions),


notation (pseudo code, flow chart, programming language), algorithmic problem solving,
simple strategies for developing algorithms (iteration, recursion). Illustrative problems: find
minimum in a list, insert a card in a list of sorted cards, guess an integer number in a range,
Towers of Hanoi.

1.1 Algorithm

An algorithm is a sequence of instruction for completing a task. Algorithm is a


sequence of finite, well-defined, unambiguous and ordered instruction. Algorithm is an
English-like representation of a logic which is used to solve the problem. Algorithm is
defined as a step by step procedure for solving any problem. It is also a precise rule (or set of
rules) specifying how to solve a problem. An algorithm is a sequence of finite instructions,
often used for calculation and data processing.

Characteristics of an algorithm

1. It is simple to understand step by step solution of the problem.


2. An algorithm is independent of programming language.
3. Algorithm is precise and unambiguous.
4. Algorithm should be written in sequence.
5. It looks like normal English.
6. Result should be obtained only after the algorithm terminates.

Qualities of an algorithm

The factors that determine the quality of algorithm are

 Algorithm should provide accurate result than others.


 It should require minimum computer memory.
 The time taken to execute any program is considered as a main quality. Lesser
the time taken better the quality.
 Procedure of an algorithm must be in a sequential form.

Representation of algorithm

 Algorithms can be expressed in any language from natural languages (like English,
French, etc.) to programming languages (like Basic, Fortran, etc.).

 Algorithm is the basis for most of the programs. Each rule in an algorithm is written
in a programming language. All these rules are collectively called a Program.
 Algorithm has a starting point and a final point. Between these two points are the
instructions that solve the problem.

 Algorithms often have steps that repeat or require decisions (such as logic or
comparison).
Example of Algorithm

1. Algorithm for finding sum of 2 numbers

Step 1: Start
Step 2: Read 2-numbers A, B.
Step 3: Add 2-numbers and store result in C.
Step 4: Display the result “C”
Step 5: Stop.

2. Algorithm for finding sum and average of n -numbers

Step 1: Start
Step 2: Read limit of n-values i.e., number of values to be added.
Step 3: Read all n-values one by one
Step 4: Calculate sum of n-values and store result in “sum”
Step 5: Calculate average on n-values using formula sum/n.
Step 6: Print sum and average.
Step 7: Stop.

3. Algorithm for find greatest of 3-numbers

Step 1: Start
Step 2: Read 3 numbers A, B and C.
Step 3: Compare A and B. If A is greater perform Step 4 else perform Step 5
Step 4: Compare A and C. If A is greater, Print “A is Big” else Print “C is Big”.
Step 5: Compare B and C, If B is greater, Print “B is Big” else Print “C is Big”.
Step 6: Stop.

4. Algorithm for find greatest of 2-numbers

Step 1: Start
Step 2: Read 2 numbers A and B.
Step 3: Compare A and B.
Step 4: If A is greater, print “A is Big” else Print “B is Big”.
Step 5: Stop.

5. Algorithm to compute factorial of a number

Step 1: Start
Step 2: Read a number “n”
Step 3: Initialize the value of variable “fact” to 1.
Step 4: Set a loop to find the factorial of the given number “n” using formula
fact=fact*i.
Step 5: Print the factorial of the given number
Step 6: Stop.
Practice algorithm for following questions

1. Algorithm to find difference and product of 2 given numbers.


2. Algorithm to find area of circle.
3. Write an algorithm to print Fibonacci series.
4. Write an algorithm to print numbers from 2 to 100.
5. Algorithm to compute Simple interest and compound interest.
6. Algorithm to find roots of quadratic equations.
7. Write an algorithm to add even numbers between 0 to 1000.
8. Algorithm to multiply two matrices.

1.2. Building Blocks of Algorithms

Algorithms can be designed using the following building blocks namely

 Statements
 State
 Control flow
 Functions

1.2.1 Statements

A statement is the smallest standalone element of an imperative programming


language that expresses some action to be carried out. It is an instruction written in a high-
level language that commands the computer to perform a specified action. A program written
in such a language is formed by a sequence of one or more statements. A statement may have
internal components (e.g., expressions).

Kinds of Statements

 Simple Statement
 Compound Statement

Simple Statement

Simple statement refers algorithm statement which contains single step or single
action.

Example

assignment statement A= A + 6, A= B+C*D


goto statement: goto label
return statement: return 0, return a
call statement: function( ), swap( )

Compound Statement

Algorithm may contain one or more statements illustrating single action is called
compound statement. Statements are enclosed between “begin” and “end” keywords.
Example

Block Statement:
begin
….
….
end
do-loop:
do
{ ….
….
}while(condtion)
for-loop:
for(condition)
{ ….
….
}
if-statement:
if(condition)
{ ….
….
}
else
{
….
….
}
switch-statement:
switch (c)
{
case ‘a’: alert();
break;
case ‘q’: quit();
break;
}
while-loop:
while(condition)
do
{
….
….
}
1.2.2 State

An algorithm is deterministic automation for accomplishing a goal which, given an


initial state, will terminate in a defined end-state. Typically, when an algorithm is associated
with processing information, data is read from an input source or device, written to an output
device, and stored for further processing. Stored data is regarded as part of the internal state
of the entity performing the algorithm. In practice, the state is stored in a data structure.

Algorithm include three different state, namely

 Initial State – Start of the algorithm


 End State – End of the algorithm
 Internal State – Include process, read data from input device, write data to
output device, storing data, etc.,

1.2.3 Control Flow

Many programming languages have what are called control flow statements; used to
determine what section of code is run in a program at a given time. Control flow is the order
of function calls, instructions, and statements are executed or evaluated when a program is
running.

Program control structures are defined as the program statements that specifies the
order in which statements are executed. A program is not limited to a linear sequence of
instructions. Understanding the logic of the program is very difficult for someone other than
developers. Hence, modification, enhancement and maintenance of these programs were very
difficult.

Sequence Control Flow

As the name suggests the sequential control structure is used to perform the actions one
after another in sequential order. It performs process A and then performs process B and so
on. This structure is represented by writing one process after another. The logic flow is top to
bottom approach.

Example

Step 1: Start
Step 2: Read limit of n-values i.e., number of values to be added.
Step 3: Read all n-values one by one
Step 4: Calculate sum of n-values and store result in “sum”
Step 5: Calculate average on n-values using formula sum/n.
Step 6: Print sum and average.
Step 7: Stop.

In the above example flow control is sequential order. All the statements are executed one
after another.
Selection Control Flow

Selection control structures (or) Decision structures allows the program to make a
choice between two alternate paths whether it is true or false. IF...THEN or IF..THEN..ELSE
or a case structures are the selection structures. This logic is used for making decisions.

Example

Step 1: if(a>b)
Step 2: print “a is greater”
Step 3: else
Step 4: print “a is greater”

In the above example flow control is selection order. If Step 1 is true, step 2 will be selected
for execution. If Step 1 is false, step 4 will be selected for execution.

1.2.4 Functions

Functions are “self contained” modules of code that accomplish a specific task.
Functions usually “take in” data, process it, and “return” a result. Once a function is written,
it can be used over and over and over again. Functions can be “called” from the inside of
other functions. Functions “Encapsulate” a task (they combine many instructions into a single
unit of code).

A function is a set of instruction that perform a specified task. Most programming


languages provide many built in functions that would otherwise require many steps to
accomplish, for example, sqrt( ), add( ), strlen( ) etc., User can also include user defined
function in which block of statements are defined by the user based on requirement.
Parameters transferred from the main program to the function definition. Parameters used
within main function are called as Actual parameter. Parameters used outside the main
function is called are Formal parameter. It is used within the function definition. Parameters
transferred from the function to the main program.

Advantages of using function

1. Big complex program can be divided into small subtasks.


2. It is very easy to locate and debug errors.
3. Function can be used wherever it is necessary.
4. Functions avoid the repetition of coding in several places. Instead function can be
called wherever it is required.
5. Functions enable a programmer to build a library of repeatedly used routines.

Example

function average_grade( list_of_grades )


....
end function
1.3. Notations

A notation is a system of characters, expressions, graphics or symbols used in


problem solving. Notation represents technical facts created to facilitate the best result for a
problem. There are various notation used in problem solving.

1.3.1 Pseudo Code

Pseudo code is an outline of a program written in the form that can be easily
converted into programming statements. Pseudo code use styled English language to
represent the process of computer program. Pseudo code is skeleton form of all programming
language.

Pseudo code is a kind of structure English for designing algorithm. Pseudo codes came
from two words. Pseudo and code pseudo means imitation and code refer to instructions,
written in a programming language.

Pseudo code cannot be compiled nor executed, and there are no real formatting or
syntax rules. The benefit of pseudo code is that it enables the programmer to concentrate on
the algorithms without worrying about all the syntactic details of a particular programming
language. In fact, you can write pseudo code without even knowing what programming
language you will use for the final implementation.

Keywords of Pseudo code

There are few standard keywords used for representing various actions. They are,
1. Input  READ, GET, INPUT
2. Output  PRINT, DISPLAY, SHOW, OUTPUT
3. Calculations  CALCULATE, COMPUTE, ADD, SUBTRACT, INITIALIZE
4. Incrementing  INCREMENT, DECREMENT

Guidelines of Pseudo code

1. Statement should be written in simple English.


2. Pseudo code should be programming language independent.
3. Pseudo code must be understandable and concise.
4. Each statement should express just one action for the computer.
5. Keyword in Pseudo code should be capitalized.

Benefits of Pseudo code

1. It is easy to develop a program from Pseudo code.


2. Pseudo code is compact, readable and easy to modify.
3. Since it is language independent, can be used by all programmers.

Limitations of Pseudo code

1. Pseudo code cannot be complied or executed.


2. These are no syntax rules, programmer use their own style.
3. It does not provide visual representation.
Example

1. Pseudo code to find sum of 2 numbers

READ A, B
COMPUTE C by adding A with B
PRINT C
STOP

2. Pseudo code to find sum and average of n-numbers

READ n
FOR (i=0;i<n;i++)
READ all inputs a[i]
END FOR
COMPUTE SUM by adding all values
CALCULATE AVG by dividing SUM by n
DISPLAY SUM and AVG
STOP

3. Pseudo code to find greatest of 2-number

READ A,B
IF (A>B)
DISPLAY “A is greater”
ELSE
PRINT :B is greater”
STOP

4. Pseudo code to find greatest of 3-number

READ A,B,C
IF (A>B)
IF (A>C)
DISPLAY “A is greater”
ELSE IF (B>C)
PRINT “B is greater”
ELSE
PRINT “C is greater”
STOP

5. Pseudo code to find sum of even numbers between 0 and 100

SET sum=0
FOR (i=0;i<=100;i++)
CALCULATE sum=sum+i
EN FOR
PRINT sum
STOP
6. Pseudo code to find sum of n-even numbers

READ n
INITIALIZE i=0
SET sum=0
DO WHILE (i<n)
COMPUTE sum=sum+i
i =i+2
END DO
WRITE sum
STOP

7. Pseudo code to find factorial of a number

READ num
INITIALIZE fact=1
FOR (i=1;i<num;i++)
fact=fact*i
END FOR
OUTPUT fact
STOP

8. Pseudo code to find addition of 2-matrices

READ A[i][j], B[i][j]


INPUT row, col
FOR (i=0;i<row;i++)
FOR (j=0;j<col;j++)
Sum[i][j]=A[i][j]+B[i][j]
END FOR
END FOR
DISPLAY sum[i][j]
STOP

9. Pseudo code to find multiplication of 2-matrices

READ A[i][j], B[i][j]


INPUT row, col
FOR (i=0;i<row;i++)
FOR (j=0;j<col;j++)
SET C[i][j]=0
FOR (k=0;k<row;k++)
C[i][j]=c[i][j]+a[i][k]*b[k][j]
END FOR
END FOR
END FOR
DISPLAY C[i][j]
STOP
1.3.2. Flowchart

A flowchart is a pictorial representation of an algorithm. 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 clearly in a visual form.
Since flowchart is a diagrammatic representation, it forms a common medium of
communication.

A flow chart is a diagrammatic representation that illustrates the sequence of operations


to be performed to arrive at the solution. Each step in the process is represented by a different
symbol and contains a short description of the process step. The flow chart symbols are
linked together with arrows showing the flow direction of the process.

Flow charts are easy to understand diagrams showing how steps in a process fit
together. This makes them useful tools for communicating how processes work, and for
clearly documenting how a particular job is done. Furthermore, the act of mapping a process
out in flow chart format helps you clarify your understanding of the process, and helps you
think about where the process can be improved.

Flowchart Symbols

A flowchart is drawn using different kinds of symbols. A symbol used in a flowchart


is for a specific purpose. Their shapes and functions are predefined in nature.

SYMBOL Name of Symbol PURPOSE


Oval represent start and stop of the
Terminal
program
Parallelogram used to get input and
Input / Output
print the output
Rectangle used for representing
Process
process, action, initialization etc.

Diamond used to represent decision


Decision Making
or branch
Circle used to connect flowchart that
Connector
is long more than one page

Flow lines Indicate the direction of flow

Preparation Used to represent for loop statement

Used to represent functions used in


Predefined Process
C program
Need for flowchart

1. Flowchart makes the logic clear.


2. Useful in coding
3. Used for effective analysis.

Guidelines for preparing a flowchart

1. Flowchart should have start and end.


2. Flowchart must have direction of flow from top to bottom; left to right properly
indicated using flow lines.
3. Flowchart may be simple or complex.
4. Standard symbol should be used for the respective action.

Advantage / Benefits

 Communication: Flowcharts are better way of communicating the logic of a system


to all concerned.
 Effective analysis: With the help of flowchart, problem can be analyzed in more
effective way.
 Proper documentation: Program flowcharts serve as a good program documentation,
which is needed for various purposes.
 Efficient Coding: The flowcharts act as a guide or blueprint during the systems
analysis and program development phase.
 Proper Testing & Debugging: The flowchart helps in debugging process.
 Efficient Program Maintenance: The maintenance of operating program becomes
easy with the help of flowchart. It helps the programmer to put efforts more
efficiently on that part.
 Complex logic: Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.
 Alterations and Modifications: If alterations are required the flowchart may require
re-drawing completely.
 No Update: As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.

Limitations / Disadvantage

1. Complex when program is very large


2. It is difficult to modify.
3. Costly and take more time
Design Structure of flow chart

There are 3 different design structure of flowchart. They are


a. Sequence control structure b. Selection control structure
c. Iterative / loop control structure

a. Sequence control structure

In sequence control structure, the steps are executed in linear order one after the other.
Flow of the control is sequential in order from top to bottom.

Example: Flowchart for finding sum of 2-numbers

Start

Read A, B
Flow of given
flowchart is
C =A+ B sequential

Print C

Stop

b. Selection control structure

In selection control structure, the step to be executed next is based on decision


taken. If condition is true one path is followed. If condition is false another path is followed.
Hence flow of control will not be in linear order.

Example: Flowchart for finding greatest of 2-numbers

Start

Read A, B

No
If Print “B is
A>B greater”

Yes

Print “A is greater”

Stop
In the above flowchart, flow of control is not in sequential order. Here if condition is
true, path towards “Yes” branch will be flowed. If condition is false, path towards “No”
branch will be flowed. Hence flow of control is selected based on a specific condition, it is
called as “Selection control flowchart”.

c. Iterative control structure

In iterative control structure, a set of particular instruction is executed repeatedly


until specified condition is true. If specified condition is false, another path is followed.
Example

Flowchart to find sum and average of n-numbers

Start

Read n

False
for (i=1;i<n;i++)

Given true statement is


True Executed repeatedly
Until for loop fails
Read n values

Sum of all values

Average = sum/n

Print sum and


average

Stop
Example Flowchart to find greatest of 3-numbers

Start

Read A,B,C

Yes No
If If
A> A>
B C

No Yes

No
If
B>
Print A Print C
C
Yes

Print B
Print C

Stop

Practise flowchart for following questions

1. Find odd or even number


2. Roots of quadratic equation
3. Multiplication of two matrix
4. Sum of even numbers
5. Factorial of given number
6. To print Fibonacci series
1.3.3 Programming Languages

Computer programming languages are used to communicate instruction to a


computer. Programming languages are based on certain syntactic and semantic rules, which
define the meaning of each programming language constructs. There are various types of
programming language constructs such as,

Machine Language

Programming language that can be directly understood and obeyed by a machine.


Different for each type of CPU, it is the native binary language consists of only two
characters: 0 and 1 of the computer. Machine Language is difficult to be read and understood
by humans. Machine language is the lowest-level programming language. Machine languages
are the only languages understood by computers.

Example

10101010
11110000
10001001
01010111

Assembly Language

Assembly languages have the same structure and set of commands as machine
languages, but they enable a programmer to use names instead of numbers. Each type
of CPU has its own machine language and assembly language, so an assembly
language program written for one type of CPU won't run on another. In the early days of
programming, all programs were written in assembly language.
An assembly language is a low-level programming language for microprocessors and
other programmable devices. It is not just a single language, but rather a group of languages.
An assembly language implements a symbolic representation of the machine code needed to
program a given CPU architecture. Assembly language is also known as assembly code
Example

Start
add x,y
sub x,y


end
High Level Language

A high level programming language consists of (English-like) “people” language to


simplify the writing computer algorithms. A high level programming language allows the
programmer to write sentences in this language which can be easily translated into machine
instructions. The sentences written in a high level programming language are called:
statements

Example: C Language to find maximum of two numbers

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter 2 numbers:");
scanf("%d%d",&a,&b);
if(a>b)
{
printf("%d is greater",a);
}
else
{
printf("%d is greater",b);
}
getch();
}

Each statement in a high level programming language is usually translated into


multiple machine instruction which can be understood by the computer.

Some well-known programming languages

Name Application area


Fortran Scientific application (FORmula TRANslator)
Cobol Business application (Common Business Oriented Language)
C System application (successor of a language called “B”)
C++ System application (successor of the language “C”)
Java General purpose (a simplification of “C++”)
C# General purpose (another simplification of “C++”)
Perl Scripting language with many string processing capabilities
Python Scripting language using indentation as block denotation.
PHP Server Scripting language
1.4. Algorithmic Problem Solving

Algorithms are procedural solutions to problems. These solutions are not answers but
specific instructions for getting answers. Algorithmic problem solving is about the
formulation and solution of problems where the solution involves principals and techniques
that have been developed to assist in the construction of correct algorithms.

Understand the problem

Decide on:
Computational means, exact vs.
approximate solving, algorithm design
technique

Design an Algorithm

Prove Correctness

Analyze the Algorithm

Code the Algorithm

a) Understanding the problem

Before designing an algorithm you have to understand completely the problem given.
Read the problem’s description carefully and ask questions if there are any doubts
about the problem, do a few small examples by hand, think about special cases, and ask
questions again if needed. An input to an algorithm specifies an instance of the problem the
algorithm solves. It is important to specify exactly the range of instances the algorithm needs
to handle.

b) Ascertaining the Capabilities of the Computational Device

Once you completely understand a problem, you need to ascertain the capabilities of the
computational device the algorithm is intended for.

Sequential algorithms: Instructions are executed one after another, one operation at a time.
Accordingly, algorithms designed to be executed on such machines.

Parallel algorithms: The central assumption of the RAM model does not hold for some
newer computers that can execute operations concurrently, i.e., in parallel.
c) Choosing between Exact and Approximate Problem Solving

The next principal decision is to choose how to solve the problem.

Solving the problem exactly is called an exact algorithm


Solving it approximately is called an approximation algorithm.

Reason to choose an approximation algorithm

First, there are important problems that simply cannot be solved exactly for most of
their instances; examples include extracting square roots, solving nonlinear equations, and
evaluating definite integrals. Second, available algorithms for solving a problem exactly can
be unacceptably slow because of the problem’s intrinsic complexity. This happens, in
particular, for many problems involving a very large number of choices. Third, an
approximation algorithm can be a part of a more sophisticated algorithm that solves a
problem exactly

d) Deciding on appropriate Data Structures

In the new world of object oriented programming, data structures play an important
role for both design and analysis of algorithms. Data structures can be defined as a particular
scheme of organizing related data items.
Algorithms + Data Structures = Programs

e) Algorithm Design Techniques

An algorithm design technique is a general approach to solving problems


algorithmically that is applicable to a variety of problems from different areas of computing.

First, they provide guidance for designing algorithms for new problems, i.e., problems
for which there is no known satisfactory algorithm. Second, algorithms are the cornerstone of
computer science. Every science is interested in classifying its principal subject, and
computer science is no exception. Algorithm design techniques make it possible to classify
algorithms according to an underlying design idea; therefore, they can serve as a natural way
to both categorize and study algorithms.

f) Methods of Specifying an Algorithm

Once an algorithm is designed, you need to specify it in some fashion. Free and also a
step-by-step form is Pseudocode. These are the two options that are most widely used
nowadays for specifying algorithms.

Pseudocode is a mixture of a natural language and programming language like


constructs. Pseudocode is usually more precise than natural language, and its usage often
yields more succinct algorithm descriptions

In the earlier days of computing, the dominant vehicle for specifying algorithms was a
flowchart, a method of expressing an algorithm by a collection of connected geometric
shapes containing descriptions of the algorithm’s steps. This representation technique has
proved to be inconvenient for all but very simple algorithms.
g) Proving an Algorithm’s Correctness

Once an algorithm has been specified, it has to be proved for its correctness. That is,
you have to prove that the algorithm yields a required result for every legitimate input in a
finite amount of time.

A common technique for proving correctness is to use mathematical induction because


an algorithm’s iterations provide a natural sequence of steps needed for such proofs.
Although tracing the algorithm’s performance for a few specific inputs can be a very
worthwhile activity, it cannot prove the algorithm’s correctness conclusively. But in order to
show that an algorithm is incorrect, you need just one instance of its input for which the
algorithm fails.

The notion of correctness for approximation algorithms is less straightforward than it is


for exact algorithms. For an approximation algorithm, we usually would like to be able to
show that the error produced by the algorithm does not exceed a predefined limit.

h) Analyzing an Algorithm

Efficiency is an important characteristic of any algorithm. There are two kinds of


algorithm efficiency: Time efficiency, indicating how fast the algorithm runs Space
efficiency, indicating how much extra memory it uses.

Another desirable characteristic of an algorithm is simplicity. Because simpler


algorithms are easier to understand and easier to program; consequently, the resulting
programs usually contain fewer bugs. Sometimes simpler algorithms are also more efficient
than more complicated alternatives. Yet another desirable characteristic of an algorithm is
generality. There are two issues here:
 Generality of the problem the algorithm solves and
 The set of inputs it accepts.

Sometimes it is easier to design an algorithm for a problem posed in more general


terms. There are situations, however, where designing a more general algorithm is
unnecessary or difficult or even impossible. As to the set of inputs, the main concern should
be designing an algorithm that can handle a set of inputs that is natural for the problem at
hand.

If users are not satisfied with the algorithm’s efficiency, simplicity, or generality, user
must return to the drawing board and redesign the algorithm. In fact, even if your evaluation
is positive, it is still worth searching for other algorithmic solutions.

i) Coding an Algorithm

Most algorithms are destined to be ultimately implemented as computer programs.


Programming an algorithm presents both a peril and an opportunity. The peril lies in the
possibility of making the transition from an algorithm to a program either incorrectly or very
inefficiently. Some influential computer scientists strongly believe that unless the correctness
of a computer program is proven with full mathematical rigor, the program cannot be
considered correct.
1.5. Simple Strategies for developing algorithms

Iteration and recursion are key Computer Science techniques used in creating
algorithms and developing software. In simple terms, an iterative function is one that loops to
repeat some part of the code, and a recursive function is one that calls itself again to repeat
the code. Using a simple for loop to display the numbers from one to ten is an iterative
process. Solving the Eight Queens Problem is a simple recursive process.

Recursion is a problem solving approach by which a function calls itself repeatedly


until some specified condition has been satisfied. Recursion splits a problem into one or
more simpler versions of itself.

Advantages of Recursive functions:

 Recursion can produce simpler, more natural solutions to a problem


 It is written with less number of statements
 Recursive functions are effective where the terms are generated successively to
compute a value
 It requires few variables which makes program clean
 It is useful for branching processes

Difference between recursion and iteration:

Recursion Iteration
Repetition is achieved through Iteration is explicitly a repetition
repeated function calls structure
Recursion terminates when a base caseIteration terminates when the loop
is recognized continuation test becomes false
Recursion causes an-
other copy of the function Iteration normally occurs within
and hence a considerable a loop, so the extra memory
memory space is occupied. assignment is omitted.

When a function call itself repeatedly until some specified condition is satisfied is
called as recursion. Recursive functions are commonly used in applications in which the
solution to a problem can be expressed in terms of successively applying the same solution to
subsets of the problem.

A classic example is the recursive method for computing the factorial of a number.
The factorial of an integer n, which is written as n!, is the result of multiplying n by all of the
positive integers less than n.
Factorial of 5  5 * 4 * 3 * 2 * 1 = 120

Recursion can be applied by the following logic

fact(5) = 5 * fact(4)
fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1

An efficient way to calculate a factorial is by using a recursive function.

Example:

def fact(int n) //Function definition


if(n!=1)
n=n*fact(n-1); //Recursive function call
return n;

Definition part of the function factorial is the result of factorial performed on a smaller
integer. By calling itself, it can multiply the number by each positive number less than it and
then return the final result. Recursive functions can be useful in other calculations, such as
calculating Fibonacci numbers or the greatest common divisor

Example algorithm for Iteration Process

 Factorial of a given number


 Reverse of a number
 Fibonacci series
 Convert the string into lowercase
 Sum of digits
 Armstrong number

Example algorithm for recursion

 Factorial of a given number using recursion


 GCD using recursion
 Tower of Hanoi using recursion
1.6. Example

Example 1: Sum of two numbers

Algorithm Flowchart

Step 1 : Start Start


Step 2 : Input the value of A and B.
Step 3 : Find the sum of A and B.
sum=A+B Read A,B
Step 4 : Print the value of sum
Step 5 : Stop.
sum== A
sum A ++BB
Pseudocode

READ the value of variables A and B.


Print sum
Find the sum.
sum = A + B.
WRITE the output of sum.
Stop
STOP

Example 2: Find the area and circumference of circle

Algorithm Flowchart

Step 1 : Start Start


Step 2 : Input the radius of the circle
Step 3 : Find the area and circumference
using the formula Read Radius r
Area = 3.14 * r *r
Circumference = 2*3.14*r
Step 4 : Print the area and circumference of Calculate
sum =A+B
the circle. Area = 3.14 * r *r
Step 5 : Stop Circumference = 2*3.14*r

Pseudocode

READ the radius of the circle Print area and


Find the area and circumference of circumference
the circle using the formula
Area = 3.14*r*r
Circumference = 2*3.14*r
Stop
WRITE the Output of area and
Circumference of the circle
Stop
Example 3: Find area of Triangle

Algorithm Flowchart

Step 1 : Start Start


Step 2 : Read the value of len and breadth.
Step 3 : Find the area
area = ½ * len * breadth Read len,b
Step 4 : Print the value of area
Step 5 : Stop.
area sum
= ½ =* Alen
+ B* b.
Pseudocode

READ the value of variables len and breadth.


Print area
Find the area.
area = ½ * len * breadth.
WRITE the output of area.
Stop
STOP

Example 4: Swapping of two numbers using temporary variable

Algorithm Flowchart

Step 1 : Start Start


Step 2 : Read the value of a and b
Step 3 : Swap the values using temp variable
t=a Read a,b
a=b
b=t
Step 4 : Print the value of a and b sumt == Aa + B
Step 5 : Stop. a=b
b=t
Pseudocode

READ the value of a,b Print a,b


Interchange the values
t=a
a=b
b=t Stop
WRITE the swapped value a,b
STOP
Example 5: Swapping of two numbers without using temporary variable

Algorithm Flowchart

Step 1 : Start Start


Step 2 : Read the value of a and b
Step 3 : Swap the values using temp variable
a=a+b Read a,b
b=a-b
a=a-b
Step 4 : Print the value of a and b sum
a = a= +A +b B
Step 5 : Stop. b=a-b
a=a-b
Pseudocode

READ the value of a,b Print a,b


Interchange the values
a=a+b
b=a-b
a=a-b Stop
WRITE the swapped value a,b
STOP

Example 6: Find whether given year is leap year or not

Algorithm Flowchart

Step 1 : Start Start


Step 2 : Read the year
Step 3 : if (year % 4) == 0 then Read year
Print “Leap year”
Step 4 : else
Print “Not leap year”
Step 5 : Stop. If
Year%4
==0
Pseudocode

READ the value of year Print leap Print not leap


IF (year % 4 = = 0) THEN
WRITE leap year
ELSE
WRITE Not leap year Stop
ENDIF
STOP
Example 7: Greatest of two given numbers

Algorithm Flowchart

Step 1 : Start Start


Step 2 : Read the A,B
Step 3 : if (a>b) then Read A,B
Print “A greater”
Step 4 : else
Print “B greater”
Step 5 : Stop. If
(A>B)
Pseudocode

READ the value of A,B Print A Print B


IF (A > B) THEN
WRITE A
ELSE
WRITE B Stop
ENDIF
STOP

Example 8: Check whether given number is odd or even

Algorithm Flowchart

Step 1 : Start Start


Step 2 : Read the value n
Step 3 : if (n%2 = = 0) then Read A,B
Print “Odd”
Step 4 : else
Print “Even”
Step 5 : Stop. If
(n%2 ==
0)
Pseudocode

READ the value of n Print odd Print “Even”


IF (n%2 = = 0) THEN
WRITE Odd
ELSE
WRITE Even Stop
ENDIF
STOP
Example 9: Find the factorial of given number

Logic: 5! = 1 * 2 * 3 *4 * 5 = Result = 120

Algorithm Flowchart

Step 1 : Start
Step 2 : Initialize value of fact and i to 1 Start
Step 3 : READ the value of n.
Initialize fact,i = 1
Step 4 : If i <= n do the following
else Goto step6.
Read n
Step 4.1 : fact = fact*i

No
Step 4.2 : i=i*+1 If
(i < n)
Step 5 : Goto step4
Yes

fact = fact * i
i=i+1
Step 6 : Print fact
Step 7 : Stop

Pseudocode Print “Even”


Set initial one to fact i
READ the value of n
Stop
WHILE (i <= n)
fact = fact*i
i = i+1
ENDWHILE
Repeat while until the condition fail
WRITE the value of fact
Stop
Example 10: Find the reverse of given number

Logic: n = 152, result = 251

Algorithm Flowchart

Step 1 : Start
Step 2 : Initialize r=0, sum=0 Start
Step 3 : READ the value of n.
r=0, sum=0
Step 4 : If n > 0 do the following
else Goto step6.
Read n
Step 4.1 : r = n % 10

No
Step 4.2 : sum = sum *10 + r If
(n > 0)
Step 4.3 : n = n / 10
Yes
Step 5 : Goto step4
r = n % 10
sum = sum *10 + r

Step 6 : Print sum n = n / 10

Step 7 : Stop

Pseudocode
Print sum
Set initial sum=0, i=0
READ the value of n
Stop
WHILE (n > 0)
r = n % 10

sum = sum *10 + r


n = n / 10
ENDWHILE
Repeat while until the condition fail
WRITE the value sum
Stop
Example 11: Find Fibonacci Series of given number

Logic: n=7
0, 1, 1, 2, 3, 5, 8

Algorithm Flowchart

Step 1 : Start
Step 2 : Initialize a=0, b=1 Start
Step 3 : READ the value of n.
a = 0, b = 1
Step 4 : FOR (i=1; i < n; i++)
Step 4.1 : WRITE a
Read n

No
Step 4.2 : c = a + b
for(i=1;i<n;i+
Step 4.3 : a = b +)
Step 4.4 : b = c Yes

Step 5 : Stop WRITE a


c=a+b
Pseudo code a=b
Set initial a=0, b=1 b=c
READ the value of n
FOR (i=1; i < n; i++)
WRITE a
c=a+b Stop
a=b
b=c
END FOR
Repeat FOR until the condition fail
Stop
1.7. Illustrative Problems

1.7.1 Find minimum in a list python:

To find the minimum value into an array of items, take the first element and compare
its value against the values of order elements. Find the minimum.

Algorithm

Step 1: Start the program


Step 2: Declare and read elements of a List
Step 3: Declare and set a variable min as First element of the list.
Step 4: Traverse the List index (i) from 1st position to n-1st position.
Step 5: If List[i]<min then
Min=List[i]
Step 6: Repeat the step until i becomes n
Step 7: Display min is the smaller number
Step 8: Stop the program

Example

List[0] 2
List[1] 3
List[2] 5
List[3] 9
List[4] 1
List[5] 6
List[6] 8
List[7] 7

Python Program

x = [2,3,5,9,1,6,8,7]
def my_min(sequence):
low = sequence[0] # need to start with some value
for i in sequence:
if i < low:
low = i
print(low)
my_min(x)
Output
1
1.7.2. Find the insert a card in a list of sorted cards

To insert a card in the sorted card, user must increase the list size with 1. User can
insert a new card in the appropriate position by comparing each element’s value with the new
card. When the position is found, user has to move the remaining elements one position up
and the card can be inserted in appropriate position

Algorithm

Step 1: Start the program


Step 2: Declare and read elements of a List(Card Deck) in sorted order
Step 3: Read a newcard element to be inserted
Step 4: Traverse the List index (i) from n-1st index to 0th position
Step 5: If newcard>List[i] then
Set Position(f) as the current index
Move the cards of fth index to n-1 index to its next index
Step 6: Display all the card elements of a new List
Step 8: Stop the program

Example

List[0] 2
List[1] 3
List[2] 4
List[3] 6
List[4] 8
List[5] 9

To insert a card with value 5:

Position to be inserted is List[3] hence move elements from List[3] one step down

List[0] 2
List[1] 3
List[2] 4
List[3]
List[4] 6
List[5] 8
List[6] 9
New List

List[0] 2
List[1] 3
List[2] 4
List[3] 5
List[4] 6
List[5] 8
List[6] 9

Python Program

import random
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
number_of_decks = 4
define function to define the cards def
cards_define_function(): cards = deck *
number_of_decks return cards
define the cards
cards = cards_define_function()
define function remove card def
remove_card(string): return
cards.remove(string)
define a function for computer cards def computer_cards():
computer_card_one = random.choice(cards)
remove_card(computer_card_one)
computer_card_two = random.choice(cards)
remove_card(computer_card_two)
computer_total = computer_card_one + computer_card_two return
computer_card_one, computer_card_two, computer_total
define a function for user’s initial cards def user_cards():
user_card_one = random.choice(cards)
remove_card(user_card_one) user_card_two =
random.choice(cards)
remove_card(user_card_two)
user_total = user_card_one + user_card_two return
user_card_one, user_card_two, user_total
define a single random card function
def one_more_card():
extra_card = random.choice(cards)
remove_card(extra_card)
return extra_card
define computer random card function def
computer_new_random_card(): computer_new_card =
random.choice(cards)
remove_card(computer_new_card)
return computer_new_card
define cards lists (user and computer)
computer_cards = list(computer_cards())
user_cards = list(user_cards())
define computer stands on
computer_stands_on = 17
define the showing functions def
computer_show():
print(“Computer has {}”.format(computer_cards)) def
user_show():
print(“You have {}”.format(user_cards)) def
bust():
print(“BUST! You lost, that was easy money for the Computer!”) def
ask_again():
new_answer = input(“Computer stands on {}. Do you want another card?
“.format(computer_stands_on))
return new_answer
define function to ask user (main function) def
ask_user_initial():
answer = input(“Your first card is {}, computer’s first card is {}, type ‘SHOW’ to
show your other card! “
.format(user_cards[0], computer_cards[0]))
if answer != ‘’:
user_show()
while user_cards[len(user_cards)-1] <= 21:
new_answer = ask_again()
if new_answer == ‘yes’ or new_answer == ‘YES’:
extra_card = one_more_card()
user_cards[len(user_cards)-1] += extra_card
print(“Your new card is a {}!”.format(extra_card))
print(“Your new total is {}”.format(user_cards[len(user_cards)-1]))
user_cards.insert(len(user_cards)-1, extra_card)
else:
case 1 while computer total < computer_stands_on -> draw card
computer has to draw its new card/cards
while computer_cards[len(computer_cards)-1] < computer_stands_on:
computer_new_card = computer_new_random_card() print(“Computer has drawn
{}”.format(computer_new_card)) computer_cards[len(computer_cards)-1] +=
computer_new_card computer_cards.insert(len(computer_cards)-1,
computer_new_card)
case 2 else show user’s and computer’s results else:
if computer_cards[len(computer_cards)-1] <= 21:
if computer_cards[len(computer_cards)-1] < user_cards[len(user_cards)-1]:
print(“Your total is {}”.format(user_cards[len(user_cards)-1])) user_show()
print(“Computer has {}”.format(computer_cards)) print(“CONGRATS, it
looks like you won this one! Let’s play again!”) break
elif computer_cards[len(computer_cards)-1] > user_cards[len(user_ cards)-1]:
print(“Your total is {}”.format(user_cards[len(user_cards)-1]))
user_show()
print(“Computer has {}”.format(computer_cards))
print(“OOOOPS, You should have asked for ANOTHER card, computer wins
AGAIN!”)
break
else:
print(“Your total is {}”.format(user_cards[len(user_cards)-1]))
print(“Computer has {}”.format(computer_cards))
print(“This is a PUSH, it was a nice hand both of you played great!”)
break
else:
print(“Your total is {}”.format(user_cards[len(user_cards)-1]))
user_show()
print(“Computer has {}”.format(computer_cards))
print(“CONGRATS, it looks like you won this one! Let’s play again!”)
break
else:
bust()
user_show()
while computer_cards[len(computer_cards)-1] < computer_stands_on:
computer_new_card = computer_new_random_card()
print(“Computer has drawn {}”.format(computer_new_card))
computer_cards[len(computer_cards)-1] += computer_new_card
computer_cards.insert(len(computer_cards)-1, computer_new_card)
computer_show()
ask_user_initial()

Output

Your first card is 2, computer’s first card is 5, type ‘SHOW’ to show your other card! 4
You have [2, 2, 4]
Computer stands on 17. Do you want another card? 2
Computer has drawn 10
Your total is 4
You have [2, 2, 4]
Computer has [5, 10, 10, 25]
CONGRATS, it looks like you won this one! Let’s play again!
1.7.3. Find the guess an integer number in a range:

To guess a number in a range of elements, input guessing number should be restricted


to the specified range. The random number is automatically generated by the system and it
can be sorted in a variable. If both the guess number and random number are same, it should
print “Good Job” else it must print whether it is greater or lesser than the random number.

Algorithm

Step 1: Start the program


Step 2: Set the variable guessesTaken=0
Step 3: Generate the Random number and store it into a variable
Step 4: Read the variable from the user with a range (1 to 100)
Step 5: If both the guess number and random number are same, then
Print “Good Job”
else
Print either lesser or greater
Step 6: Repeat Step 4 with the specified number of chances it both numbers are not same
Step 8: Stop the program

Program

import random
BOUNDS = (1, 100)
TRIES_ALLOWED = 5
the_number = random.randint(*BOUNDS)
print(“\tWelcome to ‘Guess My Number’!\n”)
print(“I’m thinking of a number between %d and %d.” % BOUNDS)
print(“Try to guess it in as few attempts as possible.\n”)
for tries in range(TRIES_ALLOWED):
guess = int(input(“Take a guess: “))
if guess > the_number:
print(“Lower...”)
elif guess < the_number:
print(“Higher...”)
else:
print(“You guessed it! The number was %d” % (the_number))
print(“And it only took you %d tries!\n\n” % (tries + 1))
break
else:
print(“You failed to guess in time!\n\n”)
Admittedly a contorted way to write a statement that works in both Python 2 and 3...
try:
input(“Press the enter key to exit.”)
except:
pass
Output

Welcome to ‘Guess My Number’!


I’m thinking of a number between 1 and 100.
Try to guess it in as few attempts as possible.
Take a guess: 3
Higher...
Take a guess: 4
Higher...
Take a guess: 99
You guessed it! The number was 99
And it only took you 4 tries!
Press the enter key to exit.

1.7.4. Find the towers of Hanoi: class Tower:

def __init__(self):
self.counter = 0
def hanoi(self,n, a, c, b):
if n == 1:
self.counter += 1
print('{0}->{1}'.format(a, b))
else:
self.hanoi(n -1, a, b, c)
self.hanoi(1, a, c, b)
self.hanoi(n-1, b, c, a)
tower=Tower()
tower.hanoi(3,"a", "c", "b")
Output

a->b a->c c->a


a->b b->c b->a
a->b

You might also like