Problem statement:
Given an array of numbers
A=[x0,x1,...x(N-1)]
Calculate the sum S(A) using recursion.
Here I am deriving the steps and providing Algorithm
2. Problem statement
•Given an array of numbers
•Calculate the sum
0 1 1
, ,... N
A x x x
0 1 1
... N
S A x x x
0 1
0 ; 1 ; , 0, 1
k
A x A x A k x k N
4. A = [2,8,12,0]
Sum_array = 0
for i in range(len(A)):
Sum_array = Sum_array + A[i]
print(Sum_array)
Iterative
5. Recursive
All we need to find in a recursive formula are:
1. Generalization of the steps: The recurrence
definition
2. Base case: The simplest case of te probe
6. 1 0 1
|step
S A x x
2 0 1 2 1 2
| |
step step
S A x x x S A x
0 1 1
| ... |
stepk k k k
step k
S A x x x S A x
1
k k k
S S x
0 1 1
... N
S A x x x
|stepk k
Let S A S
7.
1
| |
stepk k
step k
S A S A x
1
k k k
S S x
So our recursive function depends on A and k
, , 1 k
f A k f A k x
k
x A k
, , 1
f A k f A k A k
8.
, , 1
f A k f A k A k
Generalization
Base Case
What happen in the above formula when k=0
0 1
| ...
stepk k k
S A x x x
0 0
|
S A x
Step k: sum from 0 to k
Step 0: sum from 0 to 0
9.
, , 1
f A k f A k A k
Generalization
Base Case
0 0 0
| ,0
S A x f A x
def f(A,k):
if k ==0:
return A[0]
else:
return f(A,k-1) + A[k]
10. def f(A,k):
if k == 0:
return A[0]
return f(A,k-1) + A[k]
def f(A,k):
if k ==0:
return A[0]
else:
return f(A,k-1) + A[k]
# Test the code
A = [1, 5, 8, 5 -18]
N = len(A)-1 # we substract 1 because indexes start in python from 0 to len(A)-1
Sum_A = f(A,N)
print(Sum_A)
The above function computes the sum of the k first elements of the array A
If you want to calculate the sum of all the elements of the array, then let k = len(A)