ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS
Iteration and Recursion are the simple strategies for developing algorithms.
Iteration
Iteration is the process of repeating the same set of statements again and again until the condition
becomes false. Iteration is done in two ways.
i) In iteration loop, the condition is checked at the beginning of the loop. If the condition is
true, then the loop will be executed. If the condition is false, the loop will not be executed.
No
If
condition
Yes
Body of the loop
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
ii) Condition is checked at the bottom of the loop. If the condition is true, loop will be
executed. Otherwise the loop will not be executed.
Body of the loop
Yes
If
condition
No
Example: Write an algorithm, pseudo code and draw the flowchart to print the numbers from 1
to 10.
Algorithm:
1. Start
2. Initialize n=0
3. Increment n by 1
4. Print n
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
5. Check condition n<10
i. If yes goto step 3
ii. Otherwise goto step 6
6. Stop
Flowchart:
Start
n=0
n= n+1
Print n
Yes
If
n<10
No
Stop
Pseudo code:
BEGIN
OBTAIN n
INITIALIZE n=0
INCREMENT
n=n+1
DISPLAY n
IF n<10 REPEAT the loop
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
ENDIF
END
Recursion
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.
Syntax:
function():
function():
In the above syntax, function() is a function which call itself until the condition is reached.
Difference between recursion and iteration
Sl.No Recursion Iteration
1 Function calls itself until the Repetition of loop until condition
base condition is reached. false.
2 It keeps code short and It keeps the code longer.
simple.
3 It is slower due to overhead of It is faster.
maintaining the stack
4 It takes more memory. It takes less memory.
5 Tracing is difficult if any Tracing is easier if any problem
problem occurs. occurs.
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
6. It is a process always applied It is applied to the set of
to a function instructions which we want to get
repeatedly executed .
Example: Calculating factorial of a number using recursion.
Algorithm:
1. Start
2. Read n
3. Call the function fact(n)
4. Print value of the factorial
5. Stop
fact(n) function:
1. Start function
2. If n=0, return 1
3. If n>0 return function fact(n)
4. Return
Flowchart :
The recursive function used to calculate factorial of a number is
fact(n) = 1 if n=0
fact(n) =
n *fact(n-1) if n>0.
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
ROHINI COLLEGE OF ENGINEERING &TECHNOLOGY
fact(n)
Start
Read n, fact
if
Fact=fact(n)
No
Yes
Return Return
Print fact
n*fact(n-1)
1
Stop
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING