Problem: Write a recursive function named `summer` that sums up the non-negative numbers up to and including `n`, for a parameter `n`.
- Hint: Think backwards.
- Again: Recursive. No loops.
- As usual, your function should return its answer instead of printing.
- Copy/paste this main function to test your function. It will compute the sum using your way and also keep track of its own sum, and will then say whether or not your function has the correct sum.
{
int main(){
int my_sum = 0;
for(int i = 0; i < 10; i++){
my_sum += i; //incrementing my sum
//printing out the two sums
cout<<"My sum for the first "<<i<<" numbers is "<<my_sum<<endl;
cout<<"Your sum is "<<summer(i)<<endl;
//are they equal?
cout<<"They are ";
if(my_sum != summer(i))
cout<<"not ";
cout<<"equal"<<endl<<endl;
}
}
}
Edit: links are currently disabled in the forum, please use copy and paste.
The task is asking you to write a recursive function named summer.
Then you are provided a main() function to test that the summer() function you wrote works correctly.
A recursive function is a function which calls itself. Below is an example of such a function.
The important thing about recursive functions is that you need to remember to specify an end condition, otherwise they'll call themselves until the program crashes.
In your case, you have to write a similar recursive function which uses itself to sum up all numbers from 1 to n.
You have to write function summer that takes integer and returns integer.
When the function is called with i, it will return 0+1+2+..+i as answer.
It has to be recursive, i.e. it will call itself with something other than i. The return value of that call + something will produce the correct answer.