Hi, I'm having trouble getting my summation function to work using recursion.

I am reading in a set of 10 numbers from a file into an array, then printing the array out using recursion, then I have to take the summation of 1-last number in the array (Ex 1-14).

The problem is that my function currently sums all of the elements in the array( 3, 4, 34, 43, 12, 14, etc), instead of 1-14. Any help?

NOTE: This is partial code.

// main
int main(){

const int length = 10;
int Array[length];
first = &Array[0];
last = &Array[length -1];  //14 is last element in this case.

sum = sumOfInt(last);
cout << "SUM of numbers until " << *last << ": " << sum << endl << endl;

return 0;
}

//Summation recursion function
int sumOfInt(int *n)
{
  int sum;

  if (*n > 0)
  {
    sum = *n + sumOfInt(n - 1);
    return sum;
  }

}

Recommended Answers

All 6 Replies

Does this code work? There is no type for the variables first and last.

yes it does, i already mentioned in the OP that it is PARTIAL code, to clarify tho:

int* first, int* last are declared.

I am reading in a set of 10 numbers from a file into an array, then printing the array out using recursion, then I have to take the summation of 1-last number in the array (Ex 1-14).

The problem is that my function currently sums all of the elements in the array( 3, 4, 34, 43, 12, 14, etc), instead of 1-14. Any help?

I'd say this is vague enough that you really need to post all 10 numbers in the file, get rid of the "etc" (it's only 10 numbers, just list all of them), and display the output that you ARE getting as well as the output you SHOULD get.

I have some guesses on what you mean, but post them so that there can be no ambiguity.

the array contains: 3 7 9 3 8 2 10 11 4 14

and my output now is the sum of the above numbers which is 71

the correct output is 1+2+3...14, which is 105.

hope that clarifies things a bit.

the correct output is 1+2+3...14, which is 105.

Your prototype is incorrect then. The function should not be dereferencing the array and should not be dereferencing anything at all. No pointers at all.

int sumOfInt(int n)
{
  if (n > 0)
  {
    sum = n + sumOfInt(n - 1);
    return sum;
  }
}

Pass the function 14. Note that you base case (n <= 0) doesn't return anything. You should add a return value.

im using pointers to print the array in normal and reverse order..but never mind i figured it out...all i did was create another variable that isnt a pointer that holds the number in the last element of the array and passed that to the function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.