1. ## Recursive Algorithm

How do I find a recursive algorithm for finding the sum of the first n positive integers?

procedure sum of integers (n: positive integer)
if n:=1
then sum:=1
else sum:=n+ sum of (n-1)

That's what I have so far, but it still doesn't make sense to me.

2. Originally Posted by jennifer1004
How do I find a recursive algorithm for finding the sum of the first n positive integers?

procedure sum of integers (n: positive integer)
if n:=1
then sum:=1
else sum:=n+ sum of (n-1)

That's what I have so far, but it still doesn't make sense to me.

You can do this (modify the code to the proper syntax you need):

Code:
...
sum = 0;    // initialize sum
count = 1;  // initialize counter
while count <= n do
sum = sum + count;
count = count + 1;
end do;
return sum;
...
Does this make sense?

3. ## Confused

I haven't anything in my textbook like that. I am sure it is correct, but I think I would need to simplify it to use just the terms in my textbook. Are you saying what I already have is correct? oor does it need more? THANKS!

4. Chris, your algorithm is correct but is not recursive, which appears to be a requirement of the assignment based on the OP. (I could be wrong about this.)

So here is a recursive version, in no particular programming language--

Code:
function f(n)
if n = 0 then
return 0
else
return n + f(n-1)
Jennifer, you had the right idea in your original post, you just need to make your algorithm a little more programming-like. I generalized your algorithm a little by allowing for a sum of the first 0 integers; the sum is 0.

5. Originally Posted by Chris L T521
You can do this (modify the code to the proper syntax you need):

Code:
...
sum = 0;    // initialize sum
count = 1;  // initialize counter
while count <= n do
sum = sum + count;
count = count + 1;
end do;
return sum;
...
Does this make sense?
That's an iterative algorithm. You repeat an operation as many times as needed, with a loop like 'repeat', 'while' or 'for'.