I'm supposed to write a recursive Fibonacci function which produces the nth sequence, and here's what I came up with:

Code:

unsigned long int f(int x) {
int i;
//a, b, c are sequences 1, 2, 3 respectively
int a = 0, b = 1, c = 0;
if (x == 0) //sequence 0
return 0;
else if (x == 1) //sequence 1
return 1;
else {
//loop for sequence shifts
for(i = 2; i <= x; i++) {
c = a + b; //adds previous two sequences
a = b; //moves sequence 0 to 1
b = c; //moves sequence 1 to 2
}
return c;
}
}

Unless I'm misunderstanding the question, a recursive function is one that calls itself, and I'm having trouble implementing such a function into the above code. Basically, if I call the function sequentially, it works perfectly, but if I skip a number, the program crashes since it can't store the previous calculations correctly.