-
Re: Recursive function
Dear All,
The following segment is a recursive function returns the sume of an integer array given its length.
int sumArray(int anArray[], int length) {
if (length == 0)
retyrb 0;
return anArray[length] + sumArray(anArray, length);
}
Can anyone tell me where is the erros and how to revise it.
Thanks a lot.
Wah
-
There are a few possible problems:
1) array[length].... is "length" the number of elements in the array? If so, I think the first call should be array[length-1] since an array with 5 elements has indexes numbered 0 thru 4.
2) each time you recursively call this, you are passing the same value (length). That means each time, it will add the same element in the array again, and you may get stuck in a loop. You should probably decrement the index before each recursive call.
Maybe try changing it to
"return anArray[length-1] + sumArray(anArray, length-2); "
?????
-
The end-condition of recursion is length==0, but since length doesn't decrease, the end-condition will never be reached.
Further, the first element of an array has index 0. So if length==0, it will return 0 instead of the value at first position.
Code:
int sumArray (int anArray[], int length)
{
if (length < 0)
return 0;
return anArray [length] + sumArray (anArray, length-1);
}
-
>return anArray [length] + sumArray (anArray, length-1);
anArray[length] would be out-of-bounds
Code:
int sumArray (int anArray[], int length)
{
if (length == 0)
return 0;
return anArray [length-1] + sumArray (anArray, length-1);
}
is better
-
It won't work, since you'll never reach the first element of the array. But I'd not care about the out-of-bound, since anArray[-1] won't happen. If length==-1, then the function will simply return 0.
But perhaps, this is better:
Code:
int sumArray (int anArray[], int length)
{
if (length == 0)
return anArray [length];
else
return anArray [length] + sumArray (anArray, length-1);
}