Iteration and Recursion
Iteration and Recursion
RECURSION
Problem Solving: Iteration and Recursion
Many problems can be solved using either iteration or
recursion.
steps.
The number of repetitions/iterations required to solve a
problem can be determined by many different factors. E.g. To
calculate the total of your stock portfolio, you would iterate
over your stock holdings, keeping a running total until each
holding has been processed.
In this case, the number of repetitions is determined by how
many stock holdings you happen to have.
In this case, the number of repetitions is determined by how
many stock holdings you happen to have.
Iteration lends itself more readily to solving some problems
while for others recursion can seem more natural.
Iteration is a very simple, straightforward approach to
solving many common problems such as performing
calculations and processing arrays.
Iteration
• Definition
– Repetition of processing steps
– The act of repeating a process with the aim of reaching a
desired goal. Each repetition of the processing step is called
an iteration
– iteration like recursion is based on a control structure: namely
the for loop, do while , repeat until.
– Within the above control structures there is a loop repetition
test that determines when to exit from the loop. The three main
test you usually come across are
Iteration
.
**********************************************
Until i < 10
int result = 1;
***********************************************
for (int i = 0; i < exponent; ++i) {
result *= base;
}
return result;
**********************************************
while (i < 10 )
{
………
………..
...i = I + 1
}
Iteration
• Two basic examples of functions using iteration
• This function sums up and returns the result of a list of values
def sum(list) :
result = 0
for x in list
result += x
return result
– Given an array A of N integer elements return the sum of all elements in
array A .
Iteration
• This function returns the value of the base raised to the power of the exponent
package com.wrox.algorithms.iteration;
public final class PowerCalculator {
public static final PowerCalculator INSTANCE = new PowerCalculator();
private PowerCalculator() {
}
public int calculate(int base, int exponent) {
assert exponent >= 0 : “exponent can’t be < 0”; <------------ validity of exponent
int result = 1; <------------ initialize the result
for (int i = 1; i < exponent; ++i) {
result *= base; <------------ (ITERATION
}
return result;
}
}