Start simple with the first function.
In main you just get the input of n and call the function sum with n as parameter.
In sum you need only a simple for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
/*
* Returns the sum of all numbers from 0 to n inclusive
*/
int sum(int n)
{
// TODO - implement me
}
int main()
{
}
the loop sums all the values from 0 to n, although this is also doable by a known equation … you can directly compute the answer instead, but you should know how to do the loop or you will never get anywhere.
Declaring variables with the same name can cause problems. It's not good to do int i = 0 both inside and outside the loop.
You want 0 to n inclusive. Your loop isn't reaching 'n' right now.
You need a second variable to store the result of your calculation. For each number i from 0 to n, add i to the result. Return the result from your function. Remember to initialize the result to zero before the loop.
Yes, just remember to declare result with a type, and remember all your semi-colons.
int result = 0;
Also, it is perfectly fine to do this: result = result + i;
but this is the same thing and reads nicer: result += i;
The latter statement combines the addition and assignment.
@chris simms
It's always fine to learn by asking questions (unless you're on Stack Overflow), but this is some really basic stuff. I think you'd be much better off if you just worked through some C++ tutorials.
good job getting the loop.
if you are being asked to do recursion and struggled with a for loop, you need to put in some study time as you are falling behind. And I am not trying to hurt your feelings, I am trying to warn you before you get so far behind it can't be fixed.
recursion is a function that calls itself and needs a base case. See how Mbozzi flipped the logic so it would stop on zero, counting from n down to 0 instead of up, to make it easier to write? So it calls itself with the input minus 1 until the input it zero, then pops back out with the sum.
if you call it with 5, it calls itself with 5+ sum of everything to 4.
4 + sum of everything to 3. 3+ sum to 2. 2+ sum to 1. 1+ sum to zero.
zero returns zero. 1 returns 1+0. 2 returns 2+ the previous result (1+0). 3 returns 3+ the previous result (2+1+0, stored as 3). and so on.