Ok... So I have the following program:

public int seq2 (int n)
    {
        if (n <= 0)
            return 1;
        else
            return seq2 (n - 1) + 2 * n - 1;
    }

It gives the following output:

1 2 5 10 17 26 37 50 65 82

So that means seq2(0) = 1 and I see how that happened.
But I don't get the rest :/

For seq2(1), it would just go to the else statement and execute:

return seq2 (1-1) + 2 * 1 - 1
which is 0 + 2*1 -1
which is 2-1 = 1.

So it's doing seq2 (1) all over again?

Just trace it upto seq2(2) to explain please.

also, remove the = in the if(n <= 0) and trace that to seq2(2).. (that would give you all the perfect squares.)

Also... Why is recursion so hard :( !

> which is 0 + 2*1 -1
No. It is 1 + 2*1 - 1 => 2

seq2(0) returns 1, not 0.

> which is 0 + 2*1 -1
No. It is 1 + 2*1 - 1 => 2

seq2(0) returns 1, not 0.

I wrote seq2(0) = 1 :/ i meant it returns 1.

and the whole thing is (n-1) + 2 * n - 1

since n was 1, I just put in 1 instead of n :/ I like to think that my math is correct and (1-1) + 2 * 1 - 1 is the same as 0 + 2 * 1 - 1 :/ since 1 - 1 = 0. If I'm thinking the wrong way, please correct me.

My point was that you mis-wrote your function trace value sec2(1-1) + 2 * 1 - 1 is 1 + 2 * 1 - 1 which equals 2, not 1.

oh wait :/ yeah, since seq2(0) would be 1. oh ok :D the world is awesome again :D thanks for pointing it out :D I am still learning to think recursive :P Solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.