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

UNIT_I_notes_Python_studentcopy

Python notes

Uploaded by

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

UNIT_I_notes_Python_studentcopy

Python notes

Uploaded by

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

CK COLLEGE OF ENGINEERING & TECHNOLOGY

Approved by AICTE, New Delhi, Affiliated to


Anna University.
Accredited by NAAC with ‘B’ Grade, An ISO 9001:2015
Certified institute
Jayaram Nagar, Chellangkuppam, Cuddalore

CLASS – I YEAR (I SEM)


SUBJECT CODE: GE3151 (R-2021)
SUBJECT NAME: PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT –I – COMPUTATIONAL THINKING AND PROBLEM SOLVING

Fundamentals of Computing, Identification of Computational Problems, Algorithms,


building blocks of algorithms (instructions/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, and guess an
integer number in a range, Towers of Hanoi.

Fundamentals of Computing:

Computer is a programmable device that performs mathematical calculations and


logical operations it manipulates data according to the instructions.
A simple device performs complex tasks. it is a fast operating device that process store
and retrieve large amount of data very quickly and accurately.
Computer classified into two types: HARDWARE & SOFTWARE
HARDWARE

Hardware is a general term that refers to physical components of a computer system.


The process of mounting the hardware components together is called assembling.

OVERVIEW

 An electronic machine takes information from the user, process the input and gives the
output

1
 Computer performs five major operations

1. Accepts data or instructions by way of input


2. Stores data
3. Process data as required by the user
4. Results in the form of output
5. Controls all operations inside a computer

INPUT UNIT

 Input device used to convert the information to a computer.


 All the input devices perform the following functions.
 Accept the data and instructions from the outside world.
 Convert it to a form that the computer can understand.
 Supply the converted data to the computer system for further processing.

CPU (Central Processing Unit)

 Task of performing operations like arithmetic and logical operations.


 CPU takes data and instructions from the storage unit makes calculations based on
instructions then the data send back to storage unit.
 It takes all decisions.
 Example: .ALU, Control unit, Register.

2
CONTROL UNIT.
The control unit which acts like a supervisor that the things are done in proper fashion.
The control unit determines the sequence in which computer programs and instructions are
executed. It coordinates all activities of the peripheral of the computer.

ARITHMETIC LOGIC UNIT

 Perform arithmetic and logical functions of the computer. The major operations
performed by ALU are addition, subtraction, multiplication, division, logic and
comparison. Logic operations are AND, OR, XOR, NOT etc.

MEMORY UNIT

 Important task performed by computers is storing data.


 Used for storing data, data stored in digital format.
 It has two types:

1. Primary Storage device (RAM, ROM)


2. Secondary Storage device (Pen Drive, CD, DVD, Memory Card)
 Internal Storage Device (Hard Disk)

OUTPUT UNIT

 Output unit process of producing results from the data for getting user information’s.
 It also stores values after processing the inputs.
 Example: Monitor, Printer, etc.

SOFTWARE

 Set of programs can be executed sequentially


 It has two types,
1. System software- collection of programs designed to operate,
Control, and extend the processing capabilities of the computer itself.
2. Application software- designed to satisfy a particular need of a particular
Environment.
PROGRAM

 Set of instructions written in any programming language. A program controls all the
activities of the processor.
CHARACTERISTICS OF COMPUTER

 SPEED-The computer has units of speed in microsecond, nanosecond, and even


the pico second.
 ACCURACY-The calculations are 100% error free.
 STORAGE-A computer has much more storage capacity than human beings.
 AUTOMATION-Automation is the ability to perform a given task automatically.

3
 DILIGENCE-It can perform repeated tasks with the same speed and accuracy,
Unlike human beings, a computer is free from monotony, tiredness, and lack of
concentration.
 REABILITY-A computer is a reliable machine and designed to make
maintenance easy.
 VERSATALITY-This machine can be used to solve the problems related to
various fields
 COST REDUCTION.

APPLICATION OF COMPUTER

A most powerful tool used in day to-day. Some are


 It stores, displays and receive information.
 Used to draw graphs, pictures.
 Used to control robots.
 Perform clinical test.
 Perform accounting, tabulation work.
 To prefer horoscopes

IDENTIFICATION OF COMPUTATIONAL PROBLEMS

 Computer science basically designed for solving problems by using computation.

 Computation is type of calculations like arithmetic and non-arithmetic steps.

 Computational allowed identifying complex problems, understanding the problems


and developing a solution for that problem.

To solve a computational problem, two things needed,


 Representation that all the relevant aspects of the problem.
 Algorithm that solves the problem.

Types of computational problems

 Decision problems
 Search problems
 Counting problems
 Optimization problems

Decision problems

In computational theory decision problems is a yes or no question of inputs. A method for


solving a decision problem, given in the form of an algorithm is called decision procedure.

Search problems

A search algorithm which solves a search problem. A search algorithm work to retrieve
information stored within some data structure. Three types of search algorithms.

4
1. Linear search
2. Binary search
3. Hashing

Counting problems

Counting problem is the problem of finding the number of distinct elements in a data stream.

Optimization problems

An optimization problem is the problem of finding the best solution from all the feasible
solution. It can be divided into two categories, depending on whether the variables are
continuous or discrete.

 Optimization problem with discrete variable is known as discrete optimization.


 Optimization problem with continuous variable is known as continuous optimization.

ALGORITHM:

Algorithm is defined as a step by step procedure for solving any problem. The sequence
of steps to be performed in order to solve a problem by the computer is known as an
algorithm.

Characteristics of an Algorithm:
 Algorithm has a finite number of inputs.
 Every instruction should be precise and unambiguous.
 Ensure that the algorithm has proper termination.
 Effectiveness of each step is very important.
 The desired output must be obtained only after the algorithm terminates.
 The algorithm should be in sequence.

Approaches to Algorithm Design:


 Top Down
 Bottom Up

Quality of algorithm:
 Time - Lesser the time taken better the quality.
 Memory - Require minimum computer memory.
 Accuracy – Should provide accurate result.
 Sequence - Procedure of an algorithm in a sequential form.
 Generality – fit to all type of inputs.

Representation of algorithm:
 Algorithm has a starting point and a final point. Between these two points are
the instructions that solve the problem.

5
 Algorithms often have steps that repeat or require decisions.
 Algorithm can be expressed in any language from natural languages to
programming languages.

Example:
Algorithm (find the area)
Step 1: start
Step 2: Read r
Step 3: calculate area=3.14*r*r
Step 4: Display area
Step 5: Stop

REAL TIME EXAMPLE FOR ALGORITHM (ATM Machine)


Step 1: Insert Card Step 2: Select your language

Step 3 : Enter your PIN

Step 4 : Transaction Type

6
Step 5 : Account Type

Step 6 : Enter Amount

Step 7 : Take Your Money Step 8: Another Transactions

Step 9: Ending Your Session


BUILDING BLOCKS OF ALGORITHMS:

 Instruction/Statements
 State/Selection
 Control flow
 Functions

Instruction/Statements
 A statement is the smallest standalone element of a programming language that
expresses some action to be carried out.

7
 An instruction written in a high-level language that commands the computer to
perform a specified action.

 A program written in a language is formed by a sequence of one or more


statements. A statement may have internal components like expressions.
Kinds of statements:
i. Simple statements
 Assignment:A=A+67
 Goto:goto next;
 Return: return 10;
ii. Compound statements
{
Set of Statements
}
In a computer statements might include some of the following actions
 input data-information given to the program
 process data-perform operation on a given input
 output data-processed result
A statement is executed, with an expression is evaluated.
State:
 Transition from one process to another process under specified condition with
in a time is called state.
 When an algorithm is associated with processing information, data is read from
an input source or device, written to an output device, and/or stored for further
processing.
Control flow:
 Flow of control (or) control flow is the order function calls, instructions, and
statements are executed or evaluated when a program is running.
 Program control structures are defined as the program statements that specify
the order in which statements are executed.

(i) Sequence Control Structures


 Sequential control structure is used to perform the actions one after another.
 This structure is represented by writing one process after another.
(ii) Selection Control Structures
 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…ELSE or a case structures are the selection structures.
 This logic is used for making decisions.
(iii) Iteration (or) Looping (or) Repetition
 In some programs, certain set of statements are executed again and again based
upon conditional test. i.e. executed more than one time.
 This type of execution is called looping or iteration.

8
Functions
 Function is a sub program which consists of block of code (set of instructions) that
performs a particular task.
 For complex problems, the problem is being divided into smaller and simpler tasks
during algorithm design.
 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 again and again.
 Functions can be from inside of other functions.
Example: Addition of two numbers.
Step 1: Start
Step2: Call add() function
Step 3: End
add() function:
Step 1: Start add() function
Step 2: Read a,b
Step 3: c=a+b
Step 4: Display c
Step 5: End

Notations (or) Representation of an algorithm

 Pseudocode
 Flowchart
 Programming Language

(i)Pseudocode
Pseudocode came from two words. Pseudo and Code Pseudo means imitation and
Code refer to instructions written in a programming language.
Rules for writing Pseudocode
 Write one statement per line.
Each task will correspond to one line of Pseudocode. (Example READ
name,regnno,marks)
 Capitalize initial keywords.
The keywords should be written in Capital
letters(EX:READ,IF,THEN,REPEAT,ENDIF)
 Ident to show hierarchy.
Indentation is a process of showing the boundaries of the structure.
 Sequence – It keeps the statements in sequence.
 Selection – It indent the statements that fall inside the selection structure.
 Looping -It indent the statements that fall inside the loop.
EX: WHILE(i<=10) // LOOPING
If i<10 THEN // SELECTION

9
i=i+2
ELSE
i=i //SEQUENCE
ENDIF
ENDWHILE
 End multi line structure.
Each structure must be ended properly.
EX:ENDIF for IF statement
 Keep statement language independent

Table 1: Keywords for using Pseudocode


STATEMENTS KEYWORDS

Input READ,OBTAIN,GET

Output PRINT,DISPLAY,SHOW

Compute COMPUTE,CALCULATE,DETERMINE

Initialize SET,INIT
Add one INCREMENT,BUMP
Input, Output, Compute, Initialize, Add one SEQUENCE

IF,THEN,ELSE,ENDIF IF-THEN-ELSE

Sequence one THEN--IF


Sequence two ELSE—IF

End of IF conditional ENDIF


WHILE,DO,ENDWHILE LOOP

CASE,OF,OTHERS,ENDCASE A CASE
Multi-way branch based on conditions CASE

Identifier before possible CASE conditions OF


Identifier before CASE default condition, for conditions
OTHERS
not listed in the CASE expression
REPEAT,UNTIL loop REPEAT-UNTIL

REPEAT Sequence REPEAT

determines the ending point of a REPEAT Sequence UNTIL


FOR loop FOR,TO,DOWNTO,ENDFOR,DO
Iterate with index i from n to m DOWNTO

10
Iterate with index i from m to n TO

FOR Conditional followed by command FOR

End of FOR loop ENDFOR


The use of conditional statements inside of other
NESTED CONSTRUCTS
conditional statements
INVOKING SUBPROCEDURES CALL,RETURN

Calls in and executes a command CALL

returns desired information RETURN

EXCEPTION HANDLING BEGIN,EXCEPTION,WHEN,END

identifies start of BEGIN block BEGIN

identifies start of exception construct EXCEPTION

individual condition precedence for each exception type WHEN

Advantages of Pseudocode.
 Can be done easily on a word processor
 Easily modified
 No symbols are used
 It is simple because it uses English-like statements.
 No specific syntax is used.

Disadvantages of Pseudocode.
 It’s not visual
 There is no accepted standard.
 Cannot be compiled not executed.

(ii) Flowchart
 A flow chart is a diagrammatic representation that illustrates the sequence of
operations to be performed to arrive at the solutions.
 Each step in the process is represented by a different symbol and contains a of
the process step.
 The flowchart symbols are linked together with arrows showing the flow of
directions.

S.NO NAME OF SYMBOL SYMBOL DESCRIPTION

Represent the start and


1. Terminal symbols
stop of the program.

11
Denoted either an input
2. Input/output
or output operation.

Denotes the process to


3. Process symbol
be carried out

Represent decision
4. Decision
making and branching

Represent the sequence


of steps and direction of
5. Flow lines
flow .Used to connect
symbols.
A connector symbol is
represented by a circle.
6. Connectors The symbol is used to
connect more
flowcharts.

Used to call sub


7. Sub Function Call
function.

Rules for drawing a flowchart


 The standard symbols should only be used.
 The arrowheads in the flowchart represent the direction of flow in the problem.
 The direction of the flow from top to bottom (or) left to right.
 The flow lines should not cross each other.
 Keep flowchart as simple as possible.
 Words in the flowchart should be common and easy to understand.
 More than one flowcharts connected by using connectors.

Advantages of flowchart.
 Communication.
 Effective analysis.
 Proper documentation.
 Efficient coding.
 Proper Testing and Debugging.
 Efficient Program Maintenance

Limitations (or) disadvantages of flowchart


 Complex Logic
 Alteration or Modification
 No update

12
(iii) Programming Language
In computer technology, a set of conventions in which instructions for the machine are
written. There are many languages that allow humans to communicate with computers.
(a)Machine Language
 The machine language consists of binary numbers that encode instructions
for the computer.
 Every computer has its own machine language.
Example: 10110101-B5
(b)Assembler Language
 An assembler language consists of mnemonics
 There is one mnemonic for each machine instruction of the computer.
 Each assembler instruction is a mnemonic that corresponds to a unique
machine instruction.
Example:
Start
Add x,y
Sub x,y
…………….
……………..
END
(c)High level language
 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:
main()
{
if(x<y)
min=x
}

13
EXAMPLES FOR NOTATIONS:

1. Write an algorithm, pseudocode & flowchart for addition of two numbers.

Example
Algorithm (Add two numbers) Flowchart START
Step 1: Start
Step 2: Get the value of a and b.
Step 3: c=a+b Read a, b
Step 4: Display c value.
Step 5: End. C=a+b

Pseudocode
READ a, b Display C
C=a+b
WRITE C
END

2. Write an algorithm, pseudocode & flowchart to find a number is odd or even.

Algorithm :

Step 1 : Start
Step 2 : Read n
Step 3 : Check n%2==0 then
Step 4: Display n is even
Step 5: Otherwise Display n is odd Flowchart
Start 4 : Stop

Pseudocode:

READ n
IF n%2 ==0 THEN
DISPLAY “EVEN”
ELSE
DISPLAY “ODD”

14
3. Write an algorithm, flowchart & pseudocode for sum of ‘n’ numbers.

Algorithm:

Step 1: Start
Step 2: Read n, sum=0
Step 3: Initialize loop variable i=1
Step 4: Check i<=n then
Step 5: sum=sum+i
Step 6: i=i+1
Step 7: Goto step 4 until the condition gets false.
Step 8: Display sum

Pseudocode:
READ n
INITIALIZE sum=0, i=1
WHILE i<=n THEN
sum=sum+i
i=i+1
END WHILE
WRITE sum
Flowchart
Start

Read n, sum=0, i=1

False
Check i<=n

True

sum=sum+i

i =i+1

Display sum

End

15
ALGORITHMIC PROBLEM SOLVING

 Algorithms are procedural solutions to problems.


 These solutions are not answers but specific instructions for getting answers.
 The sequence of steps for designing and analyzing algorithm follows,
1. Understanding the problem.
2. Ascertaining the capabilities of the computational device.
3. Choosing between exact and approximate problem solving.
4. Algorithm design techniques.
5. Method of specifying an algorithm
6. Proving an algorithm’s correctness
7. Analyzing an algorithm.
8. Coding an algorithm.

Understand the problem

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

Design an algorithm

Prove correctness

Analyze the algorithm

Code the algorithm

Fig: Algorithm design and analysis process

16
1. Understanding The Problem:
 The given problem must be understood completely.
 An input to an algorithm specifies an instance of the problem the
algorithm solves.
2. Ascertaining The Capabilities of the Computational Device:
 After understanding a problem, ascertain the capabilities of the
computational device.
 Sequential algorithm: Instructions are executed one after another, one
operations at a time.
 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.
3. Choosing between exact and approximate problem solving:
 Solving the problem exactly is called an exact algorithm.
 Solving it approximately is called an approximation algorithm.
4. Algorithm design techniques:
 Algorithm design technique is a general approach to solving problems
algorithmically that is applicable to a variety of problems from different
areas of computing.
 It provides guidance for designing algorithms for new problem.
5. Methods of specifying an algorithm:
 Pseudo code
 Flowchart
Pseudo code:
 It is a mixture of a natural language and programming language like
constructs.
 Pseudo code is usually more precise than programming language.

Flowchart:
 Flow chart is a method of expressing an algorithm by a collection of
connected geometric shapes containing descriptions of the algorithm steps.
6. Proving an algorithm correctness:
 After specifying the algorithm, it should be proved for its correctness.
 A common technique for proving correctness is to use mathematical
induction.
 Tracing the algorithm correctness for specific inputs can be very
worthwhile activity, it cannot prove the algorithm’s correctness
conclusively.
 The notion of correctness for approximation algorithms is less straight
forward than it is for exact algorithms.
7. Analyzing an algorithm

Three Characteristics of algorithm


 Efficiency
 Simplicity
 Generality.
Efficiency:

17
There are two kinds of algorithm efficiency:
 Time Efficiency-Indicating how fast the algorithm runs
 Space Efficiency-Indicating how much extra memory it uses.

Simplicity:
 Simpler algorithms are easier to understand and easier to program.
 The resulting programs usually contain fewer bugs.
Generality:
 Generality of the problem the algorithm solves.
 The set of input it accepts.
8. Coding an Algorithm:
 Coding or programming is the process of translating the algorithm into
the syntax of a given programming language.
 Convert each step in the algorithm into one or more statements in a
programming language

REAL TIME EXAMPLES FOR PROBLEM SOLVING

1. How to remember our day to day routine activities?

Remainder (calendar) Sticky Notes

Notepad Writing Inform a friend, and ask them to


Remind you

18
Alert by Alarm

2. How to travel to place.

Looking for routes to destination Identifying the shortest path

Choose the best way to travel Pack up and start

19
SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS

Iteration and recursion are key computer science techniques used in creating
algorithms and developing software.
Iteration
 Iterative are programs that follow a path from the starting instruction till the end of the
algorithm.
 Iterative functions are on that loops to repeat some part of the code.
 Using a simple loop to display the numbers from one to ten is iterative process.
 Steps to develop an iterative algorithm:
 Define problem: The problem that needs iteration has to be identified and defined.
 Initial conditions: The condition that has to satisfied to start the iteration.
 Define loop variants: The variable that controls the number of iteration has to be
defined.
 Define step: The steps that are to be repeated must be defined.
 Define measure of progress: The loop invariant that have been defined would be
changed when algorithm progress.
 Define Exit condition: When the iteration would be stopped has to be identified.
 Make progress: Move forward after executing an instruction.

 Maintain Loop variants: In order to repeat the steps, the loop invariant must be
maintained in range.
 Ending: When the iteration has stop.

Example algorithm for iteration process:


1.Factorial of a given number.
2.Reverse of a number.
3.Sum of digits.

20
Recursion:
 Recursive function is one that calls itself again to repeat the code.
 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.
 In a recursive algorithm the algorithm calls itself with smaller input values.
 The recursive programs require more memory and computation compared with
iterative algorithms.
Example: factorial of a given number.
n!=n x (n-1)!
4!=4 x(4-1)!
=4 x (3!)
=4 x 3 x 2 x1
=24
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.
 It is useful for branching process.
Example algorithm for recursion:
 GCD using recursion.
 Factorial given number using recursion.

EXAMPLE OF ITERATION & RECURSION


1. Write an algorithm & draw flowchart to find factorial of a number using iteration?
Algorithm :

Step 1 : Start
Start 2 : Read n
Start 3 : Initialize loop variable i = 1 and fact = 1
Start 4 : Check i <= n then
Start 5 : calculate fact = fact * i
Start 6 : i=i+1
Step 7 : Go to step 4 until the condition gets false
Start 8 : Display fact
Start 8 : Stop

21
Pseudocode :

READ n
INITIALIZE i=1, fact=1
Line 1: IF i<=n THEN
COMPUTE fact=fact*1
i=i+1
GOTO line1
DISPLAY fact

Flowchart :
Start

Read n, fact=1, i=1

False
Check i<=n

True
fact = fact*i

i =i+1

Display fact

End

2. Write an algorithm & draw flowchart to find factorial of a number using


recursion?

Algorithm: fact() function:


Step 1:Start Step 1: Start fact(n) function
Step 2:Read n Step 2: Check n==1 OR n==0 then
Step 3:factorial = Call the function fact(n) Step 3: Return 1
Step 4:Display factorial Step 4: Otherwise Return n*fact(n-1)
Step 4:End

22
Pseudocode:
READ n
factorial=CALL fact(n)
WRITE factorial
fact(n)
BEGIN
IF n==1 OR n==0 THEN
RETURN 1
ELSE
RETURN n*fact(n-1)
ENDIF
END

Flowchart:

Start

Read n fact(n)

True
factorial=fact(n)
Check
n==0||n==1 Return 1

False
Display factorial

Return n*fact(n-1)

End

23
ILLUSTRATIVE PROBLEMS:

1.To find a minimum in a list:


Problem statement: Find in a minimum in a list.
Problem description:
Minimum in a list of elements can be achieved in different ways.
One way is to sort the list of element in ascending order and get the first element
as minimum.
Another method is to compare each element with other.
Assume the first element as minimum element and start comparing with the next
element.
If the next element is smaller than the second of its minimum and keep repeating
the procedure till the last element
Algorithm:
Step 1: Start
Step 2: Get the list of elements.
Step 3: Assume first element as Min.
Step 4: Compare Min with next element
Step 5: Check Min < next element then
Step 6: Set Min=next element
Step 7: Repeat step 4,5&6 till the last element.
Step 8: Display Min as the minimum element of the list.

24
2. Inserting a card in a list of sorted cards
Problem Statement:
Imagine that you are playing a card game. You are holding the cards in your hand, and
these cards are sorted. You are given exactly one new card. You have to put it into the correct
place so that the cards you are holding are still sorted.

25
Pseudocode:
BEGIN
READ n
FOR i=0 to n THEN
READ a[i]
i=i+1
END FOR
READ item
FOR i=n-1 to 0 and item<a[i] THEN
CALCULATE a[i+1]=a[i]
i=i-1
END FOR
ASSIGN a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n then
DISPLAY a[i]
i=i+1
END FOR
END
Flowchart

26
3. GUESSING AN INTEGER NUMBER IN A RANGE

Problem Statement:
Imagine you are trying to guess a number in a range. The objective is to randomly
generate integer number from 0 to n. Then the player has to guess the number. If the player
guesses the correctly, output an appropriate message.
ALGORITHM:
Step 1: Start
Step 2: Generate a random number and call it num.
Step 3: Repeat the following steps until the player has guessed the correct number.
Step 3.1: Enter the number to guess.
Step 3.2: Check guess==num

27
Print “You guessed the correct number”
Otherwise check guess <num

print “ Your guess is lower than the number. Guess again!”


otherwise
print “Your guess is higher than the number. Guess again!”
Step 4: End

PSEUDOCODE 1:
BEGIN
READ Guess_num,input_num
IF guess_num>input_num THEN
WRITE “Your guess is higher than the input_number!”
ELSE IF guess_num<input_num THEN
WRITE “Your guess is lower than the input_number!”
ELSE
WRITE “You guessed the correct number!”
END IF
END
Flowchart

28
4.TOWER OF HANOI:
Problem Statement:
The smaller one sits over the larger one. The objective is to move the entire disk to some
another tower without violating the sequence of arrangement.
Rules to be followed:
1. Only one disk can be moved among the towers at any given time.
2. Only the “Top” disk can be removed.
3. No large disk can sit over a small disk.

29
Algorithm:
Step 1 :Start
Step 2: Read n,source,dest,aux
Step 3:Call Tower(disk,source,dest,aux)
Step 4:Stop
Tower() Function
Step 1: Start Tower(disk, source, dest, aux)
Step 2: Check disk == 1, THEN
Step 3: move disk from source to dest
Step 4: Otherwise
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
Step 5: Repeat Step1 until the last disk moved.
Step 6: Return

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

30
FLOWCHART

Pseudocode:
BEGIN
READ disk, source, dest, aux
CALL MoveTower(disk,source,dest,aux)
END
FUNCTION MoveTower(disk, source, dest, aux):
IF disk == 0, THEN:
move disk from source to dest
ELSE:
MoveTower(disk - 1, source, aux, dest) // Step 1 above
move disk from source to dest // Step 2 above
MoveTower(disk - 1, aux, dest, source) // Step 3 above
END IF

31

You might also like