May 5, 2010
Recursive sum function
Array recursive sum problem
Given an array of N integers. Write a recursive function to calculate the sum of all elements in the array.
Recursive sum algorithm
The sum of N elements in a list is equivalent to the sum of one element of the array and the rest N-1 elements
Code
The following is a suggested solution in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$A[0] = 4; $A[1] = 7; $A[2] = 9; $A[3] = 5; $N = 3; $sum = FindSum($A, $N); echo "Sum = " . $sum . "n"; function FindSum($A, $N) { if ($N == 0) return $A[$N]; else return $A[$N] + FindSum($A, $N-1); } |