Help With Recursion

I am not asking for you do my homework im just really confused on the question that is being asked can anyone explain what my HW is asking?

Create a method that uses a loop to calculate the summation. Should have the same signature as the recursive method below but use a loop instead.

THANK YOU !!!

int sum(int n)

{

if (n < 1)

{

return 0;

}

return sum(n-1) + n;

}
Well basically that function uses recursion to do the following:
Return the sum of all of the numbers going to 0 from the number you typed in.

So, for example
If you pass in 3, it returns 6, because 3+2+1 = 6
If you pass in 4, it returns 10, because 4+3+2+1 = 10

Etc.


The assignment wants you to write a for loop to get the same result rather than use recursion.

It's rather simple. I'm guessing you're just over complicating it.

1
2
3
4
5
6
7
8
9
int sum(int n)
{
	int returnsum = 0;
	for (int i = 1; i <= n; i++) //For each number counting up to 'n'
	{
		returnsum += i; //Add this number to our returnsum
	}
	return returnsum; //return our returnsum
}
Last edited on
Topic archived. No new replies allowed.