Python Unit 1
Python Unit 1
(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA
SCIENCE
231GES201T –PYTHON PROGRAMMING
Unit I -Notes
I YEAR –B.E/B.TECH
(Common to all Branches)
PREPARED BY APPROVED BY
J.PRIYA HOD
1
UNIT I
ALGORITHMIC PROBLEM SOLVING
1.PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating
number of solutions. The problem solving process starts with the problem
specifications and ends with a Correct program.
Input Output
algorithm
Properties of Algorithms
❖ Should be written in simple English
❖ Each and every instruction should be precise and unambiguous.
❖ Instructions in an algorithm should not be repeated infinitely.
❖ Algorithm should conclude after a finite number of steps.
❖ Should have an endpoint
❖ Derived results should be obtained only after the algorithm terminates.
2
Memory – To execute a program, computer system takes some amount of memory
space. The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and such
algorithms may be suitable.
Example:
Example
Write an algorithm to print “PSPP”
Step 1: Start
Step 2: Print “PSPP”
Step 3: Stop
• Statements
• State
• Control flow
• Functions
1. Statements:
Reserved words - words that have pre-defined meanings in the Java language
Identifiers - words that are created by programmers for names of variables, functions,
classes, etc.
Literals - literal values written in code, like strings or numbers
Operators - special symbols that perform certain actions on their operands
Calls to functions
2. State:
3
State is the information that the program manipulates to accomplish some task.
It is data or information that gets changed or manipulated throughout the runtime of a
program. The state of an algorithm is defined as its condition regarding stored data.
Example: state refers to the set of variables and the values to which they refer.
3. Control flow:
Control flow is the order that instructions are executed in a program .A control
statement is a statement that determines the control flow of a set of instructions
The control can be executed in three ways
1. sequence
2. selection
3. Iteration
Sequence:
All the instructions are executed one after another is called sequence execution.
Pseudocode Flowchart
BEGIN
statement
Statement Action1
END
Action2
Example:
Add two
numbers
Selection:
It is provided by a control statement that selectively executes instructions.
4
Example
Write an algorithm to check whether he is eligible to
vote? Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to
vote” Step 4: else print “Not eligible to
vote” Step 6: Stop
Algorithm to find biggest among 2 nos
Step1: Start
Step 2: Get two numbers as input and store it in to a and b
Step 3: If a is greater than b then
Step 4: Print a is big
Step 5: else
Step 6: Print b is big
Step 7:Stop
5
Iteration:
Example
Algorithm to print first 10 natural numbers
Step1: Start
Step 2: Initailize a=0
Step 3: Check whether a<=10,then goto step 4
Step 4: a=a+1,Print the value of a
Step 5: Else goto Step 6
step 6:Stop
4. Functions:
❖ For complex problems, the problem is been divided into smaller and simpler
tasks during algorithm design.
6
Benefits of Using Functions
❖ Reduction in line of code
❖ code reuse
❖ Better readability
❖ Information hiding
❖ Easy to debug and test
❖ Improved maintainability
Example:
• Function: piece of prewritten code that performs an operation
• print function: displays output on the screen
• Argument: data given to a function
Example: data that is printed to screen
Types of functions/categories of functions:
Pre-defined functions-built in functions provided by programming languages
Example: print() in python
User-defined functions-created by user.
Example fact()
Pseudocode:
BEGIN BEGINPROCEDURE
CALLPROCEDURE statement1
END statement2
END PROCEDURE
Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
7
3.NOTATIONS
3.1.FLOW CHART
8
Rules for drawing a flowchart
1. The flowchart should be clear, neat and easy to follow.
2. The flowchart must have a logical start and finish.
3. Only one flow line should come out from a process symbol.
4. Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol.
Advantages of flowchart:
1. Communication: - Flowcharts are better way of communicating the logic of a
system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in
more effective way.
3. Proper documentation: -Program flowcharts serve as a good
program documentation, which is needed for various purposes.
9
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. 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.
Disadvantages of flow chart:
1. Complex logic: - Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may
require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
4. Cost: For large application the time and cost of flowchart drawing becomes
costly.
Example1:Flowchart for calculating simple interest
10
3.2.PSEUDO CODE:
Pseudo code derived from ‘pseudo’ which means imitation and ‘code’ means instruction
is a generic way of describing an algorithm without using any specific programming
language related notations. Pseudocode is an artificial and informal language that helps
programmers to develop algorithms.
Characteristics/properties of Pseudocode:
• It is a “text based” detail (algorithmic) design tool.
• Pseudo code generally consists of short English phrases to express a specific task
• Consists of natural language-like statements that precisely describe the steps of an
algorithm or program
• Statements describe actions
• Focuses on the logic of the algorithm or program
• Avoids language-specific elements
Advantages of Pseudocode:
• Its language independent nature helps the programmer to express the design in
plain natural language.
• Based on the logic of a problem it can be designed without concerning the syntax
or anyrule
• It can be easily translated into any programming language.
• It is compact in nature and can be easily modify.
• To develop a pseudocode it requires less time and effort than other programming
tools.
Disadvantages/ Limitations of Pseudocode:
• It is unable to provide the visual presentation of the program logic.
• It has not any standard format or syntax of writing.
• It cannot be compiled or executed.
• To convert a pseudocode into flowchart is not easy
Example1: Calculate Area and Circumference of a Circle
READ radius of the circle as r
CALCULATE area== 3.14*r* r
CALCULATE circumference = 2* 3.14 *r
PRINT area
PRINT circumference
12
Syntax for if else: Example: Greates of two numbers
IF (condition)THEN BEGIN
statement READ a,b
... IF (a>b) THEN
ELSE DISPLAY a is greater
statement ELSE
... DISPLAY b is greater
ENDIF END IF
END
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-value) DO BEGIN
statement GET n
... FOR (1to n)DO
ENDFOR PRINT i
ENDFOR
END
13
3 Does use symbols Use keywords Use standardized
and programming symbols
language constructs
4 Set of instructions Artificial and A graphical way of
Informal writing pseudocode
language
3.3.PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a computer
to perform specific tasks. The programmers have to follow all the specified rules before
writing program using programming language. The user has to communicate with the
computer using language which it can understand.
Types of programming language
1. Machine language
2. Assembly language
3. High level language
Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In
machine language the different instructions are formed by taking different
combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language which the computer understands. For
executing any program written in any programming language, the conversion to
machine language is necessary. The program written in machine language can be
executed directly on computer. In this case any conversion process is not required.
High speed
The machine language program is translation free. Since the conversion time is
saved, the execution of machine language program is extremely fast.
Disadvantage:
➢ It is hard to find errors in a program written in the machine language.
➢ Writhing program in machine language is a time consuming process.
Machine dependent: According to architecture used, the computer differs from each
other. So machine language differs from computer to computer. So a program
developed for a particular type of computer may not run on other type of computer.
Assembly language:
➢ To overcome the issues in programming language and make the programming
process easier, an assembly language is developed which is logically equivalent to
machine language but it is easier for people to read, write and understand.
14
➢ Assembly language is symbolic representation of machine language.
Assembly languages are symbolic programming language that uses symbolic
notation to represent machine language instructions. They are called low
level language because they are so closely related to the machines.
Ex: ADD a, b
Assembler:
Assembler is the program which translates assembly language instruction in to
a machine language.
Advantage:
➢ Easy to understand and use.
➢ It is easy to locate and correct errors.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine
depends on the architecture of that computer.
Hard to learn
It is machine dependent, so the programmer should have the
hardware knowledge to create applications using assembly language.
Less efficient
➢ Execution time of assembly language program is more than machine
language program.
➢ Because assembler is needed to convert from assembly language to
machine language.
High level language
High level language contains English words and symbols. The specified rules
are to be followed while writing program in high level language. The interpreter or
compilers are used for converting these programs in to machine readable form.
Translating high level language to machine language
The programs that translate high level language in to machine language are
called interpreter or compiler.
Compiler:
A compiler is a program which translates the source code written in a high
level language in to object code which is in machine language program. Compiler
reads the whole program written in high level language and translates it to machine
language. If any error is found it display error message on the screen.
Examples: C and C++ compilers.
15
Interpreter
Interpreter translates the high level language program in line by line manner.
The interpreter translates a high level language statement in a source program to a
machine code and executes it immediately before translating the next statement.
When an error is found the execution of the program is halted and error message is
displayed on the screen. The python is an example of interpreter.
16
3 It is a faster process It is a slow process because
the interpreter has to wait
while each instruction is
being translated
4 Examples: C,C++ Examples :Python
Advantages
Readability
High level language is closer to natural language so they are easier to learn
and understand
Machine independent
High level language program have the advantage of being portable
between machines.
Easy debugging
Easy to find and correct error in high level language
Disadvantages
Less efficient
The translation process increases the execution time of the program. Programs
in high level language require more memory and take more execution time to execute.
4. ALGORITHMIC PROBLEM SOLVING:
Algorithmic problem solving is solving problem that require the formulation of an
algorithm for the solution. Algorithmic problem solving means solving the problem by
means of algorithm.
Understanding the Problem
The problem given should be understood completely. Check if it is similar to some
standard problems & if a Known algorithm exists. Otherwise a new algorithm has to be
developed It is the process of finding the input of the problem that the algorithm solves.
Once a problem is understood, we need to know the capabilities of the computing device this
can be done by knowing the type of the architecture, speed & memory availability.
Choosing between Exact and Approximate Problem Solving
Once algorithm is developed, it is necessary to show that it computes answer for all the
possible legal inputs. The solution is stated in two forms, exact solution or approximate
solution. Examples of problems where an exact solution cannot be obtained are
i) Finding a square root of number. ii) Solutions of nonlinear equations.
Deciding a data structure:
❖ Data structure plays a vital role in designing and analysis the algorithms.
❖ Some of the algorithm design techniques also depend on the structuring data
specifying a problem’s instance
❖ Algorithm+ Data structure=programs.
17
Algorithm Design Techniques
❖ An algorithm design technique(or “strategy” or “paradigm”)is a general
approach to solving problems algorithmically that is applicable to a variety of
problems from different areas of computing.
❖ Learning these techniques is of utmost importance for the following reasons.
❖ First, they provide guidance for designing algorithms for new problems,
❖ Second, algorithms are the cornerstone of computer science
18
Proving an Algorithm’s Correctness
❖ Once an algorithm has been specified, you have to prove 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.
Analysing an Algorithm
1. Efficiency.
Time efficiency: Indicating how fast the algorithm runs,
Space efficiency: Indicating how much extra memory it uses.
2. simplicity.
❖ An algorithm should be precisely defined and investigated with mathematical
expressions.
❖ Simpler algorithms are easier to understand and easier to program.
❖ Simple algorithms usually contain fewer bugs.
Coding an Algorithm
❖ Most algorithms are destined to be ultimately implemented as computer
programs.Programminganalgorithmpresentsbothaperilandanopportunity.
❖ A working program provides an additional opportunity in allowing an empirical
analysis of the underlying algorithm. Such an analysis is based on timing the
program on several inputs and then analyzing the results obtained.
19
Example:
Problem: To find the factorial of a number (using While loop)
Description: factorial of a number n!=n*(n-1)! Where n is the number for which factorial
is to be calculated
Solution: The algorithm, pseudocode and flowchart are as follows:
Algorithm:
step 1. Start
step 2. Read the number n
step 3. Initialize i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact =fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
5.1. Recursions:
❖ A function that calls itself is known as recursion.
❖ Recursion is a process by which a function calls itself repeatedly until some
specified condition has been satisfied.
❖ Recursion is a programming technique that comes from recurrence relation,
where the problem is divided further in sub problems smaller in size but same
in nature.
❖ This division stops when the problem cannot be divided further.
❖ This point is called base case from where control moves back towards the
original problem by solving sub problems and assembling results in order to get
the final result.
20
Advantages:
The main advantage recursion provides to programmers is that it takes less code to write
comparative to iterative version. The code written with help of recursion is more concise,
cleaner and easier to understand.
There are some data structures you will see which are quite easy to code with help of
recursion. Tree traversals, quick, and merge sort are a few examples.
Disadvantages: Recursion provides no storage saving, nor time.
Example:
Problem: To find the factorial of a number (using Recursion)
Factorial of n
Factorial of any number n is denoted as n! and is equal
to
n! = 1 x 2 x 3 x … x (n – 2) x (n – 1) x n
Example
3! = 1 x 2 x 3
=6
Factorial Function using recursion
F(n)=1 when n = 0 or1
= F(n-1) when n > 1
Example
Find 3!
We know,
F(n)=1 when n = 0 or1
= n x F(n-1) when n > 1
So,
F(3) = 3 x F(3-1) = 3 x F(2)
and F(2) = 2 x F(2-1) = 2 x F(1)
Now, F(1) = 1
Therefore,
F(2) = 2 x F(1) = 2 x 1 = 2
and, F(3) = 3 x F(2) = 3 x 2 = 6
Solution: The algorithm, pseudocode and flowchart are
as follows:
Main function:
Step1: Start
Step2: Get n
Step3: call
factorial(n)Step4:
print fact Step5:
Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
21
Step2: else fact=n*factorial(n-1) and return fact
recursion:Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
22
More examples:
Write an algorithm to find area of a rectangle
23
Write an algorithm for Calculating simple interest
Step 1: Start
Step 2: get P, n, r value BEGIN
Step3:Calculate READ P, n, r
SI=(p*n*r)/100 CALCULATES
Step 4: DisplayS SI=(p*n*r)/100
Step 5:Stop DISPLAY SI
END
24
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
25
To check positive or negative number
Step 1: Start
Step 2: get num
Step 3: check if(num>0) print a is positive
Step 4: else num is negative
Step 5: Stop
BEGIN
READ num
IF (num>0) THEN
DISPLAY num is positive
ELSE
DISPLAY num is negative
END IF
END
26
To check odd or even number
Step 1: Start
Step 2: get num
Step 3: check if(num%2==0) print num is even
Step 4: else num is odd
Step 5:Stop
BEGIN
READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END
27
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END
28
BEGIN
GET n
IF(n==0) THEN
DISPLAY “ n is zero”
ELSE
IF(n>0) THEN
DISPLAY “n is positive”
ELSE
DISPLAY “n is positive”
END IF
END IF
END
29
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 8
Step 5: Print i value
step 6 : increment i value by 1
Step 7: go to step 4
Step 8: Stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
30
Write an algorithm to print n odd numbers
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check if(i<=n) goto step 5 else goto step 8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
31
Write an algorithm to print n even numbers
Step 1: start
step 2: get n value
step 3: set initial value i=2
step 4: check if(i<=n) goto step 5 else goto step8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=2
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
32
Write an algorithm to print squares of a number
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
33
Write an algorithm to print to print cubes of a number
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i *i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i*i
i=i+2
ENDWHILE
END
34
Write an algorithm to find sum of a given number
Step 1: start
step 2: get n value
step 3: set initial value i=1, sum=0
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate sum=sum+i
step 6: increment i value by 1
step 7: goto step 4
step 8: print sum value
step 9: stop
BEGIN
GET n
INITIALIZE i=1,sum=0
WHILE(i<=n) DO
sum=sum+i
i=i+1
ENDWHILE
PRINT sum
END
35
Write an algorithm to find factorial of a given number
Step 1: start
step 2: get n value
step 3: set initial value i=1, fact=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate fact=fact*i
step 6: increment i value by 1
step 7: goto step 4
step 8: print fact value
step 9: stop
BEGIN
GET n
INITIALIZE i=1,fact=1
WHILE(i<=n) DO
fact=fact*i
i=i+1
ENDWHILE
PRINT fact
END
36
ILLUSTRATIVE PROBLEMS
1.Find Minimum in a List
Problem Specification
Consider the following requirement specification:
A user has a list of numbers and wishes to find the minimum value in the list. An
Algorithm is required which will allow the user to enter the numbers, and which will
calculate the minimum value that is input. The user is quite happy to enter a count of
the numbers in the list before entering the numbers.
Finding the minimum value in a list of items isn‟t difficult. Take the first element and
compare its value against the values of all other elements. Once we find a smaller
element we continue the comparisons with its value. Finally we find the minimum.
ALGORITHM
Step 1: Start
Step 2: Declare variables N, E, i and MIN.
Step 3: READ total number of element in the List as N
Step 4: READ first element as E
Step5: MIN=E
Step6: SETi=2
Step 7: IF i>n go to Step 12 ELSE go to step 8
Step 8: READ ith element as E
Step 9: IF E < MIN THEN SET MIN = E
Step 10: i=i+1
Step 11: go to step 7
Step 12: Print MIN Step 13: Stop
PSEUDOCODE
READ total number of element in the List as N READ first element
as E
SET MIN =E SET i=2 WHILE i<=n
READ ith element as E IF E < MIN THEN
SET MIN = E
ENDIF
INCREMENT i by ONE
ENDWHILE
PRINTMIN
37
FLOWCHART
38
2. Insert a Card in a List of Sorted Cards
Problem Specification:
Insert a Card in a List of Sorted Cards – is same as inserting an element into a sorted
array.
We start from the high end of the array and check to see if that's where we want to
insert the data. If so, fine. If not, we move the preceding element up one and then
check to see if we want to insert x in the “hole” left behind. We repeat this step as
necessary.
Thus the search for the place to insert x and the shifting of the higher elements of the
array are accomplished together
ALGORITHM
Step 1: Start
Step 2: Declare variables N, List[], i, and X.
Step 3: READ Number of element in sorted list as N
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i = N-1
Step 11: IF i>=0 AND X<List[i] THEN go to step 12 ELSE go to step15
Step 12: List[i+1]=List[i]
Step 13: i=i-1
Step 14: go to step 1
Step 15: List[i+1]=X
39
Pseudocode
READ Number of element in sorted list as N
SET i=0 WHILE i<N
READ Sorted list element as List[i]
i=i+1
ENDWHILE
READ Element to be insert as X SET i = N-1
WHILE i >=0 and X < List[i] List[i+1] =List[i]
i = i – 1 END WHILE
List[i+1] = X
FLOWCHART
40
3. Guess an Integer Number in a Range
ProblemSpecification:
Let's play a little game to give an idea of how different algorithms for the same
problem can have wildly different efficiencies. The computer is going to randomly
select an integer from 1 to N and ask you to guess it. The computer will tell you if each
guess is too high or too low. We have to guess the number by making guesses until you
find the number that the computer chose. Once found the number, think about what
technique used, when deciding what number to guess next?
ALGORITHM:
Step 1: Start
Step 2: SET Count =0
Step 3: READ Range as N
Step 4: SELECT an RANDOMNUMBER from 1 to N as R
Step 5: READ User Guessed Number as G
Step 6: Count = Count +1
Step 7: IF R==G THEN go to step 10 ELSE go to step 8
Step 8: IF R< G THEN PRINT “Guess is Too High” AND go to step 5 ELSE go to step9
Step 9: IF R>G THEN PRINT “Guess is Too Low” AND go to step 5
Step 10: PRINT Count as Number of Guesses Took
Pseudocode:
SET Count =0 READ Range as N
SELECT an RANDOM NUMBER from 1 to N as R WHILE TRUE
READ User guessed Number as G Count =Count +1
IF R== G THEN
BREAK ELSEIF R<G THEN
DISPLAY “Guess is Too High” ELSEIF R>G THEN
DISPLAY “Guess is Too Low”
ENDWHILE
DISPLAY Count as Number of guesses Took
41
FLOWCHART:
42
4.Tower of Hanoi
Problem Specification
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and
more than one rings is as depicted in Figure 1.8. These rings are of different sizes and
stacked upon in an ascending order, i.e. the smaller one sits over the largerone.
The mission is to move all the disks to some another tower without violating the
sequence of arrangement. A few rules to be followed for Tower of Hanoiare:
Rules:
Only one disk can be moved among the towers at any given time. Only the
"top" disk can be removed.
No large disk can sit over a small disk.
Step by Step Moves in Solving Three Disk Tower of Hanoi Problem Algorithm
43
ALGORITHM:
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this
problem with lesser amount of disks, say → 1 or 2. We mark three towers with name,
source, destination and aux (only to help moving the disks). If we have only one disk,
then it can easily be moved from source to destination tower.
If we have 2 disks −
• First, we move the smaller (top) disk to aux tower.
• Then, we move the larger (bottom) disk to destination tower.
• And finally, we move the smaller disk from aux to destination tower.
So now, we are in a position to design an algorithm for Tower of Hanoi with more than
two disks. We divide the stack of disks in two parts. The largest disk (nth disk) is in one
part and all other (n-1) disks are in the second part.
Our ultimate aim is to move disk n from source to destination and then put all other (n-
1) disks onto it. We can imagine to apply the same in a recursive way for all given set of
disks.
The steps to follow are −
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest
A recursive Step based algorithm for Tower of Hanoi can be driven as follows −
Step 1: BEGIN Hanoi(disk, source, dest, aux)
Step 2: IF disk == 1 THEN go to step 3 ELSE go to step 4
Step 3: move disk from source to dest AND go to step 7
Step 4: CALL Hanoi(disk - 1, source, aux, dest)
Step 5: move disk from source to dest
Step 6: CALL Hanoi(disk - 1, aux, dest, source)
Step 7: END Hanoi
44
Pseudocode:
A recursive Pseudocode for Tower of Hanoi can be driven as follows –
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1 THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1 move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
Flowchart:
45