I am not familiar with c++ enough

I am tasked to do this:

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
			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;
				}
			}
		}


I do not understand what the task is telling me to do. could anyone help me solve and explain it a little?
If you are "not familiar with C++ enough" you will want to read at least some portions of the C++ Tutorial:

http://cplusplus.com/doc/tutorial/

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

void sayHello(int times)
{
    if (times == 0) // ending condition
        return;

    std::clog << "Hello!\n";
    sayHello(times - 1);
}

int main()
{
    sayHello(5);
}
Hello!
Hello!
Hello!
Hello!
Hello!


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.
Last edited on
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.
@Catfish3 What is the standard clog?
It's like std::cout (or simply cout if you're using namespace std;).
http://cplusplus.com/reference/iostream/
clog is output stream like cout and cerr, but less commonly used.
i know about using namespace std just didnt know about the clog
Topic archived. No new replies allowed.