Help
I am lost. Please help me, with the following problem. Thank you.
// write a recursive method that will compute the sum of the first n i
// integers in an array of a least n integers. Hint Begin with n^th integer?
( is this corect?
Public void recSum ( int n, int myarray)
int sum = 0;
for (int counter = ^th; counter <= n; ++counter) { sum == counter: }
do you want the sum of the first n numbers in the array?
Public void recSum ( int n, int myarray)
int sum = 0;
for (int counter = 0; counter < n; ++counter)
{
sum+= myarray[counter]
}
-Bz
@Ecuador123: No, that's not correct. That's not recursion.
@Bz_Unknown: That's not recursion either. That's still iteration.
Hint: a recursive function that produces a sum will probably have to return something, almost certain the sum itself.
Message was edited by:
paulcw
Eckie,
just a few pointers.
* a recursive function is one that calls its self.... so in your case sum would call the sum function.
* a recursive function needs an exit condition, to stop it from calling its self endlessly... this exit condition is (almost) always checked first thing.
* "divide and concure"... recursive algorithms commonly divide the problem into parts (usually halves) then call themselves to solve each of the parts of the problem... which can be much more efficient. The [url=http://linux.wku.edu/~lamonml/algor/sort/quick.html]quick sort[/url] is an exmaple.
* recursion is "dangerous", because it risks filling the stack. In the real world it is used judiciously... mainly with tree structures of unknown size, like a file find... where the maximum size of the dataset is known before hand.
Keith.
While you are obviously doing homework and you should figure it out... here is a
solution. But read it carefully to make sure you know whats going on!
public int recursiveSum ( int n, int[] arrayOfAtleastNintegers) {
if(arrayOfAtleastNintegers.length <n) {
throw new java.lang.IllegalArgumentException("n must be less than size of array!");
}
if (n >= 0) { // remember that 0 is the first Array Element
return arrayOfAtleastNintegers[n] + // Start with the Nth element as per your hint.
recursiveSum(n-1,arrayOfAtleastNintegers); // decrement you index n and recursively call the method.
}
return 0; //end recursions
}