GE3151- PROBLEM SOLVING AND PYTHON PROGRAMMING- UNIT-I NOTES
GE3151- PROBLEM SOLVING AND PYTHON PROGRAMMING- UNIT-I NOTES
COMPUTER:
A computer is an electronic device that uses raw information as data and processes it
accordingly to give the required result. The main function of the computer is to store, retrieve,
and process data. Now a day’s its uses have been extended to type documents, play online
games, web browsing, editing & creating spreadsheets, office presentations, PowerPoint
meetings & video consoles, etc..
Memory
The technology behind the primary generation computers was a fragile glass
device, which was called vacuum tubes. These computers were very heavy and really large in
size. These weren’t very reliable and programming on them was a really tedious task as they
used high-level programming language and used no OS. First-generation computers were used
for calculation, storage, and control purpose. They were too bulky and large that they needed a
full room and consume rot of electricity.
• ENIAC: Electronic Numerical Integrator and Computer, built by J. Presper Eckert and
John V. Mauchly was a general-purpose computer. It had been very heavy, large, and
contained 18,000 vacuum tubes.
• EDVAC: Electronic Discrete Variable Automatic Computer was designed by von
Neumann. It could store data also as instruction and thus the speed was enhanced.
• UNIVAC: Universal Automatic Computer was developed in 1952 by Eckert and Mauchly.
Speed and size Very slow and very large in size (often taking up entire room).
Examples of the first generation IBM 650, IBM 701, ENIAC, UNIVAC1, etc.
Transistors were invented in Bell Labs. The use of transistors made it possible to
perform powerfully and with due speed. It reduced the dimensions and price and thankfully
the warmth too, which was generated by vacuum tubes. Central Processing Unit (CPU),
memory, programming language and input, and output units also came into the force within
the second generation.
Programming language was shifted from high level to programming language and
made programming comparatively a simple task for programmers. Languages used for
programming during this era were FORTRAN (1956), ALGOL (1958), and COBOL (1959).
Power and size Smaller in size, low power consumption, and generated less.
Examples of second PDP-8, IBM1400 series, IBM 7090 and 7094, UNIVAC 1107, CDC
generation 3600 etc.
During the third generation, technology envisaged a shift from huge transistors to
integrated circuits, also referred to as IC. Here a variety of transistors were placed on silicon
chips, called semiconductors. The most feature of this era’s computer was the speed and
reliability. IC was made from silicon and also called silicon chips.
A single IC, has many transistors, registers, and capacitors built on one thin slice of
silicon. The value size was reduced and memory space and dealing efficiency were increased
during this generation. Programming was now wiped out Higher level languages like BASIC
(Beginners All-purpose Symbolic Instruction Code). Minicomputers find their shape during
this era.
Examples of third generation IBM 360, IBM 370, PDP-11, NCR 395, B6500, UNIVAC 1108, etc.
4) Fourth Generation Computers: Micro-processors (1971-Present)
In 1971 First microprocessors were used, the large scale of integration LSI circuits
built on one chip called microprocessors. The most advantage of this technology is that one
microprocessor can contain all the circuits required to perform arithmetic, logic, and control
functions on one chip.
Main electronic Very large-scale integration (VLSI) and the microprocessor (VLSI has
component thousands of transistors on a single microchip).
Input/output devices pointing devices, optical scanning, keyboard, monitor, printer, etc.
Examples of fourth
generation IBM PC, STAR 1000, APPLE II, Apple Macintosh, Alter 8800, etc.
The technology behind the fifth generation of computers is AI. It allows computers to
behave like humans. It is often seen in programs like voice recognition, area of medicines, and
entertainment. Within the field of games playing also it’s shown remarkable performance
where computers are capable of beating human competitors.
The speed is highest, size is that the smallest and area of use has remarkably
increased within the fifth generation computers. Though not a hundred percent AI has been
achieved to date but keeping in sight the present developments, it is often said that this dream
also will become a reality very soon.
Input / output Trackpad (or touchpad), touchscreen, pen, speech input (recognize
device voice/speech), light scanner, printer, keyboard, monitor, mouse, etc.
Characteristics:
• Speed, Accuracy
• Storage and Retrieval
• Repeated Processing Capabilities
• Reliability, Flexibility, Low cost
• This unit can store instructions, data, and intermediate results. This unit supplies
information to other units of the computer when needed. It is also known as internal
storage unit or the main memory or the primary storage or Random Access Memory
(RAM).
• Its size affects speed, power, and capability. Primary memory and secondary memory are
two types of memories in the computer. Functions of the memory unit are −
• It stores all the data and the instructions required for processing.
• It stores intermediate results of processing.
• It stores the final results of processing before these results are released to an output
device.
• All inputs and outputs are transmitted through the main memory.
Control Unit
This unit controls the operations of all parts of the computer but does not carry out any
actual data processing operations.
Language Processors:
Assembler: This language processor converts the program written in assembly language into
machine language.
Interpreter: This language processor converts High-Level Language program into machine
language by converting and executing it line by line.
Compiler: It also converts the HLL program into machine language but the conversion manneris
different. It converts the entire HLL program in one go and reports all the errors of the program
along with the line numbers.
Software: Software represents the set of programs that govern the operation of a computer
system and make the hardware run. This type of software is tailor-made software according to a
user’s requirements.
System Software maintain the system resources Application software is built for specific
and gives the path for application software to run. tasks.
Low level languages are used to write the system While high level languages are used to
software. write the application software.
System software runs when the system is turned While application software runs as per
on and stop when the system is turned off. the user’s request.
Analog computers
Digital Computers
1. These computers take the input in the form of digits & alphabets & converted it into
binary format.
2. Digital computers are high speed, programmable electronic devices.
3. Signals are two level of (0 for low/off 1 for high/on).
4. Accuracy unlimited.
Examples: Computer used for the purpose of business and education is also an example of
digital computers.
Hybrid Computer
Super Computer
Mainframes
Mini Computer
1. These computers are preferred mostly by small type of business personals, colleges etc.
2. These computers are cheaper than above two.
3. It’s an intermediary between microcomputer and mainframe.
Micro Computer/ Personal Computer
Notebook Computers
1. Notebook computers typically weigh less than 6 pounds and are small enough to fit easily
in abriefcase.
2. The principal difference between a notebook computer and a personal computer is the
displayscreen.
3. Many notebook display screens are limited to VGA resolution.
PROGRAMMING LANGUAGES:
There are two major types of programming languages. Low-Level Languages and High-Level
Languages. Low-Level languages are further divided into Machine language and Assembly
language.
• Low-Level Languages: The term low level means closeness to the way in which the
machine has been built. Low-level languages are machine oriented and require
extensive knowledge of computer hardwareand its configuration.
• Machine Language: Machine Language is the only language that is directly understood by
the computer. It does not need any translator program. We also call it machine code and
it is written as strings of 1's (one) and 0’s (zero). When this sequence of codes is fed to
the computer, it recognizes the codes and converts it into electrical signals needed to run
it.
Advantage:
• Program of machine language run very fast because no translation program is required
for the CPU.
Disadvantages:
• It is very difficult to program in machine language. The programmer has to know details
of hardware to write a program.
• The programmer has to remember a lot of codes to write a program which results in
programerrors.
• It is difficult to debug the program.
Assembly Language:
• It is the first step to improve the programming structure. You should know that
computer can handle numbers and letter. Therefore, some combination of letters can be
used to substitute for anumber of machine codes.
• The set of symbols and letters forms the Assembly Language and a translator program is
required to translate the Assembly Language to machine language.
• This translator program is called `Assembler'. It is considered to be a second-generation
language.
Advantages:
• The symbolic programming of Assembly Language is easier to understand and saves a lot
oftime and effort of the programmer.
• It is easier to correct errors and modify program instructions.
• Assembly Language has the same efficiency of execution as the machine level language.
Because this is a one-to-one translator between assembly language program and its
corresponding machine language program.
Disadvantages:
High-Level languages:
• You know that assembly language and machine level language require deep
knowledge of computer hardware whereas in a higher language you have to know
only the instructions in English words and logic of the problem irrespective of the type
of computer you are using.
• Higher level languages are simple languages that use English and mathematical
symbols like +,-, %, / for its program construction.
• You should know that any higher-level language has to be converted to machine
language forthe computer to understand.
• Higher level languages are problem-oriented languages because the instructions are
suitablefor solving a particular problem.
• For example, COBOL (Common Business Oriented Language) is most suitable for a
business-oriented language where there are very little processing and huge output.
• There are mathematically oriented languages like FORTRAN (Formula Translation)
and BASIC (Beginners All-purpose Symbolic Instruction Code) where very large
processing isrequired. Thus, a problem-oriented language designed in such a way that
its instruction may be written more like the language of the problem. Example,
businessmen use the business term and scientists use scientific terms in their
respective languages.
• Higher level languages have a major advantage over machine and assembly languages
thathigher level languages are easy to learn and use.
• It is because that they are similar to the languages used by us in our day-to-day life.
COMPUTER HARDWARE:
Computer hardware comprises the physical part of a computer system. It includes the all-
important components of the central processing unit (CPU) and main memory. It also includes
peripheral components such as a keyboard, monitor, mouse, and printer.
• The central processing unit (CPU) is the “brain” of a computer system, containing
digital logiccircuitry able to interpret and execute instructions.
• Memory is where currently executing programs reside, which the CPU can directly and
very quickly access. Main memory is volatile; that is, the contents are lost when the
power is turned off. In contrast, secondary memory is nonvolatile, and therefore
provides long-term storage of programs anddata.
1. Primary / Main memory: Primary memory is the computer memory that is directly
accessible by CPU. It is comprised of DRAM and provides the actual working space to the
processor. It holds the data and instructions that the processor is currently working on.
2. Secondary Memory / Mass Storage: The contents of the secondary memory first get
transferred to the primary memory and then are accessed by the processor, this is
because the processor does not directly interact with the secondary memory.
The memory devices used for primary The secondary memory devices are magnetic
memory are semiconductor memories. and optical memories.
Primary memory is also known as Main Secondary memory is also known as External
memory or Internal memory. memory or Auxiliary memory.
Examples: RAM, ROM, Cache memory, PROM, Examples: Hard Disk, Floppy Disk, Magnetic
EPROM, Registers, etc. Tapes, etc.
• Input/output devices include anything that allows for input (such as the mouse and
keyboard) or output (such as a monitor or printer).
• Finally, buses transfer data between components within a computer system, such as
between theCPU and main memory.
Devices:
1. Storage Devices: Hard Drive, CD Drive, USB Stick, DVD Drive, SD Card
2. Input Devices: Keyboard, Mouse, Scanner, OCR Reader, Webcam, Touch Screen,
Microphone
3. Processing Devices: CPU, GPU
4. Output Devices: Printer, Monitor, Projector, Speakers, Headphones, Tv Screen
5. Communication Devices: Modem, Wifi card, Network card, Bluetooth
OPERATING SYSTEMS:
• An operating system is software that has the job of managing and interacting with the
hardware resources of a computer.
• It is intrinsic to the operation a computer; it is referred to as system software.
• It acts as the “middle man” between the hardware and executing application programs
• It also provides a particular user interface.
• It determines the “look and feel” of the user interface and how the user interacts with the
system,and not the particular model computer.
The syntax of a language is a set of characters and the acceptable arrangements (sequences) of
those characters.
The semantics of a language is the meaning associated with each syntactically correct sequence
of characters.
Program Translation - A central processing unit (CPU) is designed to interpret and execute a
specific set of instructions represented in binary form (i.e., 1s and 0s) called machine code.
A compiler is a translator program that translates programs directly into machine code to
beexecuted by the CPU.
An interpreter executes program instructions in place of (“running on top of”) the CPU.
Program Debugging: Syntax Errors Vs. Semantic Errors
Program debugging is the process of finding and correcting errors (“ bugs”) in a
computerprogram.
Syntax errors:
They are caused by invalid syntax (for example, entering prnt instead of print). Since a
translator cannot understand instructions containing syntax errors, translators terminate
whenencountering such errors indicating where in the program the problem occurred.
Semantic errors
Generally called logic errors are errors in program logic. Such errors cannot be
automatically detected, since translators cannot understand the intent of a givencomputation.
Dividend Remainder
4/2 = 2 0
2/2 = 1 0
1/2 = 0 1
Step 2: Now, write the remainder in reverse chronological order. (i.e from bottom to top).
Here, the Least Significant Bit (LSB) is 0 and the Most Significant Bit (MSB) is 1.
Hence, the decimal number 4 in binary is 1002
So, if we want to find how many bits does 4 in binary have? we have to count the number of
zeros and ones.
So, 4 in binary is 1002. Here, there are 2 zeroes and 1 one. Hence, we have 3 bits.
Therefore, the number of bits does 4 in binary have is 3.
TO SOLVE A PROBLEM
Representation
Captures all the relevant aspects of the problem. A representation that leaves out details of
whatis being represented is a form of abstraction.
• A farmer went to a market and purchased a wolf, a goat, and a cabbage. On his way home,
the farmer came to the bank of a river and rented a boat. But crossing the river by boat, the
farmer could carry only himself and a single one of his purchases: the wolf, the goat, or the
cabbage.
• If left unattended together, the wolf would eat the goat, or the goat would eat the
cabbage.
• The farmer's challenge was to carry himself and his purchases to the far bank of the river,
leaving each purchase intact.
The first step that must be taken is to let the goat go across the river, as any other actions will
result in the goat or the cabbage being eaten. When the farmer returns to the original side, he
has the choice of taking either the wolf or the cabbage across next. If he takes the wolf across, he
would have to return to get the cabbage, resulting in the wolf eating the goat. If he takes the
cabbage across second, he will need to return to get the wolf, resulting in the cabbage being
eaten by the goat. The dilemma is solved by taking the wolf (or the cabbage) over and bringing
the goat back. Now he can take the cabbage (or the wolf) over, and finally return to fetch the
goat.
• Computational problem solving does not simply involve the act of computer
programming.
• It is a process, with programming being only one of the steps.
• Before a program is written, a design for the program must be developed.
• Before a design can be developed, the problem to be solved must be well understood.
• Once written, the program must be thoroughly tested.
Step 1: Problem Analysis-Understanding the Problem
• Once a problem is clearly understood, the fundamental computational issues for solving it
can bedetermined.
• For the Man, Cabbage, Goat, Wolf (MCGW) problem, a brute-force algorithmic
approach of trying all possible solutions .Small number of steps for reaching a solution.
• (example)For both the Traveling Salesman problem and the game of chess, the brute-
force approach is infeasible.
For some problems, there is only one solution. For others, there may be a number (or infinite
number) of solutions. Program may be stated as finding,
• A solution
• An approximate solution
• A best solution
• All solutions
For the MCGW problem, there are an infinite number of solutions.
Finally, for the game of chess, the goal (solution) is to win the game.
In the Traveling Salesman problem there is only one solution.
For the Calendar Month problem, the data include the month and year, the number of days in
each month, and the names of the days of the week.
For the Traveling Salesman problem, the distance between each pair of cities must be
represented.
• When solving a computational problem, either suitable existing algorithms may be found
or newalgorithms must be developed.
• For the MCGW problem, there are standard search algorithms that can be used.
• For the Traveling Salesman problem, there are various (nontrivial) algorithms that can be
utilized.
• Algorithms that work well in general but are not guaranteed to give the correct result for
each specific problem are called heuristic algorithms.
Step 3: Program Implementation
• Design decisions provide general details of the data representation and the algorithmic
approaches for solving a problem.
• The details, however, do not specify which programming language to use, or how to
implement the program. That is a decision for the implementation phase. Since we are
programming in Python, the implementation needs to be expressed in a syntactically
correct and appropriate way, using the instructions and features available in Python.
Step 4: Program Testing
ALGORITHM:
Characteristics:
Representation of Algorithms:
Series – The steps must be in particular order and each of the steps must be used.
Specific – A step must not be replaced by similar step.
Steps – Each action to be done is a step.
Solve – An algorithm produces final result or output which is the solution to the problem.
Particular problem – The algorithm for one problem will not usually solve a different
problem.
Statements-Most algorithms have these basic statements.
Description of the problem-Setup, Parameters, Execution, Conclusion
State:
Transition from one process to another process under specified condition with in a time is
called state.
Control flow:
The process of executing the individual statements in a given order is called control flow.
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.
Example: Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
Selection:
A selection statement causes the program control to be transferred to a specific part of the
program based upon the condition. If the conditional test is true, one part of the program will be
executed, otherwise it will execute the other part of the program.
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
Iteration:
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.
Example
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 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
One or more steps are performed repeatedly. One or more instructions may be
executed several times depending on some conditions.
Example: To compute and print the sum and average of ten numbers.
Start
Initialize variables sum and avg to be 0
Repeat step 4 and step 5 for 10 times
Read the value of number
Add the value of the number to the sum
Calculate the average using avg=sum/10
Print the sum and avg value.
Stop
Functions:
Example:
Algorithm for addition of two numbers using function
Main function ()
Step 1: Start
Step 2: Call the function add ()
Step 3: Stop
Basic Syntax
function name(parameters) function statementsend function
4. NOTATIONS
1. Draw a flow chart to print the first ‘n’ prime numbers. (8MARKS) (JAN 2017)
2. Present the flow of execution for a while statement. (2MARKS) (JAN 2019)
3. List the symbols used in drawing a flowchart. (2MARKS)(APR 2019)
4. Draw a flowchart to accept three distinct numbers, find the greatest and print the result.
(8MARKS)(JAN 2022)
5. Draw a flowchart to find the sum of the series. (8MARKS)(JAN 2022)
1+2+3+……+100
Pseudocode is a formal design tool. It is also a programming analysis tool, that is,
commonly used in planning the program logic, where ‘pseudo’ means ‘initiation’, ‘code’ means
the set of statements or instructions written in programming language. It is also called as
‘Program Design language (PDL)’. During the design of Pseudocode, the designer or programmer
concentrate only on the logic of the program without worrying about the syntax of the
instructions. Hence pseudocode cannot be understood by the computer.
Examples:
The following control structures are also used while writing the Pseudocode
• Sequence
• Selection / condition
• Iteration
Sequence:
Selection or Conditional:
In selection, the step to be executed next is based on a decision taken. There are 2main
selection constructs – if-statement and case statement. In the if-statement, if the condition is
true then the THEN part is executed otherwise the ELSE part is executed. The case statement
is used when there are number of conditions to be checked. Depending on the value of
expression, one of the conditions is true, and the corresponding statements are executed. If
no match, then the OTHERS option which is also the default option is executed.
IF-statement
IF(condition) THEN
Statement
ENDIF
IF-ELSE statement
IF (condition) THEN
Statement 1
ELSE Statement 2
ENDIF
Case statement
CASE expression
Condition 1: Statement 1
Condition 2: Statement 2
..
..
Condition N: Statement N
OTHERS: default statement
INPUT mark
CASE based on mark
CASE mark>=90 PRINT Grade S
CASE mark>=80 PRINT Grade A
CASE mark>=70 PRINT Grade B
CASE mark>=60 PRINT Grade C
CASE mark>=55 PRINT Grade D
CASE mark>=50 PRINT Grade E
OTHERS PRINT Fail
Iteration:
• Iteration is used in the place where repetition of several lines of code is necessary.
• For, while and do-while are the iterative statements.
• For loop, repeats the execution of the statements for the specified number of times.
For count=min to max
Statements
Next count
WHILE loop execute the statements while the condition is true. In a WHILE loop thecondition is
checked at the start of the loop whereas in a DO- WHILE loop the condition is checked at the end
of the loop. So, the DO-WHILE loop executes at least once even if the condition is false when the
loop is entered.
WHILE (Condition)
Statement 1
Statement 2
..
ENDWHILE
Example: To add from 1 to 100
INITIALIZE SUM to ZERO
INTIALIZE I to ZERO
WHILE (I less than equal to 100)
INCREMENT I
ADD I to SUM and store in SUM
ENDWHILE
PRINT SUM
STOP
FLOW CHART
Flowchart Symbols: A flowchart is drawn using different kinds of symbols. A symbol used in
the flowchart is for a specific purpose. The flowchart symbols are available in most word
processors facilitating the programmer to draw a flowchart on the computer using word
processor.
Table 1: Flowchart Symbols
S.No Name of Symbol Type Description
symbol
1. TerminalSymbol Oval Represent the start and stop of the
program.
• In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
• The flow chart should be clear, neat and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
• The usual directions of the flow of a procedure or system is from left to right or top to
bottom.
• Only one flow line should come out from a process symbol.
• Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, cap leave the decision symbol.
• Only one flow line is used in conjunction with terminal symbol.
• If flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines.
• Ensure that flowchart has logical start and stop.
Advantages of Flowchart:
• Communication: Flowcharts are better way of communicating the logic of the system.
• Effective Analysis: With the help of flowchart, a problem can be analyzed in more
effective way.
• Proper Documentation: Flowcharts are used for good program documentation, which
is neededfor various purposes.
• Efficient Coding: The flowcharts act as a guide or blue print during the system analysis
andprogram development phase.
• Systematic Testing and Debugging: The flowchart helps in testing and debugging the
program
• Efficient Program Maintenance: The maintenance of operating program becomes easy
with the help offlowchart. It helps the programmer to put efforts more efficiently on that
part.
Disadvantages of Flowchart:
• Complex Logic: Sometimes, the program logic is quite complicated. In that case
flowchart becomes complex and difficult to use.
• Alteration and Modification: If alterations are required the flowchart may require re-
drawing completely.
• Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
• Sequence: In a sequence, the steps are executed in linear order one after the other.
Selection:
In a selection operation, the step to be executed next is based on a decision taken. If the
condition is true (yes), a path is followed and if the condition is false (no), then a different path
is followed.
Example1: To find the maximum of any three numbers
Example2: To display the grade for the marks obtained
Iteration:
In iterative operation, a condition is checked. Based on the result of this conditional check
(true or false), different paths are followed. Either the next step in the sequence is executed or
the control goes to one of the already executed steps to make a loop. In for loop, the statements
are repeated for specified number of times. Loop starts at min and ends with max. It has
incrementation part where the no. Of times the loop is executed is incremented. It has a
condition check part, which checks whether the loop has to be repeated or not.
Example: To add 10 numbers
while and do-while loop executes the statement while the condition is true.
Programming Language:
In general Programming languages are classified into three types. They are
• Low – level or Machine Language
• Intermediate or Assembly Language
• High – level Programming language
Machine Language
Assembly Language
An assembly language contains the same instructions as a machine language, but the
instructions and variables have names instead of being just numbers. An assembler language
consists of mnemonics, mnemonics that corresponds unique machine instruction.
Example: add x,y, sub x,y, start
Figure: Interpreter
Figure: Compiler
• It is the process of finding the input of the problem that the algorithm solves.
• It is very important to specify exactly the set of inputs the algorithm needs to handle.
• A correct algorithm is not one that works most of the time, but one that works Correctly
for alllegitimate inputs.
• If the instructions are executed one after another, it is called sequential algorithm
Choosingbetween Exact and Approximate Problem Solving
• The next principal decision is to choose between solving the problem exactly or solving it
approximately.
• Based on this, the algorithms are classified as exact algorithm and approximation
algorithm. 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
Analyzing an Algorithm:
• Efficiency
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses
• 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:
Iteration:
• The iteration is when a loop repeatedly executes till the controlling condition becomes
false
The iteration is applied to the set of instructions which we want to get repeatedly executed.
• Iteration includes initialization, condition, and execution of statement within loop and
update(increments and decrements) the control variable.
• A sequence of statements is executed until a specified condition is true is called iterations.
for loop, While loop
Recursions:
Main function:
Main function:
BEGIN
GET nCALL
factorial (n)
PRINT factEND
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial (n-1)
Flow Chart
6. ILLUSTRATIVE PROBLEMS
1. Write a recursive algorithm to solve Towers of Hanoi problem. (8MARKS) (JAN 2019)
2. Write an algorithm to insert a card in a list of sored cards. (8MARKS) (JAN 2019)
3. State the Towers of Hanoi problem. Outline a solution to the Towers of Hanoi problem with
relevant diagrams . (8MARKS) (JAN 2022)
Start
Declare hidden, guess, range = 1 to 100
Compute hidden = Choose a random value in a range
Read guess
If guess = hidden, then print “Guess is hit” else print “Guess not hit”
Stop
Pseudocode:
Algorithm:
Start
Read n
Initialize i=0
If i < n, then goto step 5 and 6 else goto step 7
Read a[i]
i=i+1 goto step 4
Compute min=a [0]
Initialize i=1
If i < n, then go to step 10 else goto step 14
If a[i] < min, then goto step 11, 12 else goto 12
min=a[i]
i=i+1 goto 7
Print min
Stop
Pseudocode:
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, THEN
CALCULATE min=a[i]
INCREMENT i
ELSE
PRINT min
ENDIF
END FOR
Flowchart:
INSERT A CARD IN A LIST OF SORTED CARDS
Problem Description:
Finding minimum in a list Problem description: The problem is to find the minimum
element in the given list of elements. Finding minimum in a list of elements can be achieved in
different ways. One way is to sort the list of elements in ascending order and get the first
element as minimum. Another method is to compare each element with other. As an initial step,
first element of the list is considered as minimum element. And in each iteration, each element in
the list is compared with the minimum. If the element in the list is less than the minimum then
swap both elements else compare with the next element in the list. These steps are continued
until the end of the list and finally print the minimum.
Algorithm:
Start
Read n
Initialize i=0
If i<n, then goto step 5, 6 else goto step 7
Read a[i]
i=i+1 goto step 4
Read item
Calculate i=n-1
If i>=0 and item<a[i], then go to step 10, 11 else goto step1210. a[i+1]=a[i]
i=i-1 goto step 7
Compute a[i+1]=item
Compute n=n+1
If i<n, then goto step 15, 16 else goto step 16
Print a[i] and increment i and goto step 14
Stop
Pseudocode:
READ n
FOR i=0 to n
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i] THEN
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n,
PRINT a[i]
INCREMENT i
END FOR
Flowchart:
TOWER OF HANOI
Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C)
and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest
disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire
stack to another rod (here considered C).
Rules:
• Only one disk can be moved at a time.
• Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
• No disk may be placed on top of a smaller disk.
The steps are
i) Move the top n-1 disks from the left pole to the centre pole, n is the number of disks.
ii) Move the nth largest disk to the right pole.
iii) Move the n-1 disks on the centre pole to the right pole.
Start
Read n
Calculate move=pow(2,n)-1
Function call T(n,Beg,Aux,End)
recursively until n=0
If n=0, then goto step 9
else goto step 6
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End) # Move disk from source to destination
T(n-1,Aux,Beg,End)
Stop
Pseudocode:
READ n
CALCULATE move=pow(2,n)-1
FUNCTION T(n,Beg,Aux,End)
Recursively until n=0
PROCEDURE
IF n==0
THEN
No disk to move
ELSE
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End)#move disk from source to destination
T(n-1,Aux,Beg,End)
END IF
END PROCEDURE
Flowchart: