1. Recursive sequence

We have a sequence of numbers "5,2,1,0,1,-2,5,...."
Write a recursive function which returns the 6th number of this sequence.
I have done recursive functions like fibonacci or pow but not something simillar to this so if someone can point me in the right direction that would be awesome.

2. What determines the sequence? Like, what is the formula specified for the nth term, or what is the recurrence relation?

If you don't know anything about how the sequence is to be determined, then just given the first few terms of the sequence, you cannot do more than guess as to what comes next, and your guess could be wrong.

EDIT:
Also, are you sure that the requirements specify that you only need to "write a recursive function which returns the 6th number of this sequence"? If so, then if the given sequence is numbered starting from the 1st number, all you need to do is to write a function that returns -2. You can satisfy the "recursive" part in any way you like, and technically your answer would be correct. Rather, I expect that the function would return the nth term, and the example is that the 6th term is -2.

3. That's all we were given and the maximum n-th term to be searched for is 6 so it doesn't matter what follows

4. Originally Posted by Tobias Mihel
That's all we were given and the maximum n-th term to be searched for is 6 so it doesn't matter what follows
Ah. In that case, the given list exhaustively defines the sequence, so that is fine. In that case, a simple solution is to store the sequence in an array, then write a recursive function to obtain the desired element. A little silly when you can access the element directly, of course, but I guess it is practice for recursion.

Alternatively, you can try figuring out a formula for the nth term given those terms.

5. Yeah I tried but the sequence is really weird ...

6. Maybe, but after reading your post #5, I have figured out a recurrence relation for the given terms. Give it a try, or use the lame array idea, whatever you will.

7. ok i wrote it
Code:
```int rek(int i)
{
if(i>2)
return -2*rek(i-1)+rek(i-2);
if(i==2) return i;
else return 1;
}```

8. Are you numbering the terms starting from 0 or 1? Either way, it looks wrong to me: rek(1) = 1, but if you number from 0, then rek(1) should equal 2, and if you number from 1, rek(1) should equal 5.

9. return 5 sorry i pasted wrong

10. Right. Looks correct to me

Now, you just need to indent your code by more than just a space...

Popular pages Recent additions