Question

My professor has asked us to write a program that uses recursion to solve a fibonacci sequence. This is all pretty normal, but he's asked us to make our function return void. I've been working at this for a few days now and can't find a way to do this.

I have:

void fibonacci(double *n,double *x,double *y,double *result) {
     if(*n == 1)
          *result = 0;
     else if(*n == 2)
          *result = 1;
     else
          fibonacci(--n,n,(n-1),(n+(n-1))); }

Is what I'm doing right? I have never had to use parameters in such ways before and I'm not sure if I'm on the right track. For some reason it's not compiling at the recursive call to fibonacci, stating invalid pointer addition. Thanks!

Was it helpful?

Solution

Since this is a homework, I won't provide working code, although a few points here:

  1. Using a reference is simpler than using pointers
  2. You really need to increase the result, not set it to 0 or 1. Therefore you need to pass to first function call by reference an int with assigned value of 0.
  3. Consider the formula: f(n) = f(n-1) + f(n-2) for all n > 2; f(n) = 0 for n=1 and f(n) = 1 for n=2.

OTHER TIPS

Hint: problem is there: fibonacci(--n,n,(n-1),(n+(n-1))); or even just there --n. You're working with pointers

The compiler is right. You need to dereference the pointers in the call, if you use pointers.

But the simpler solution would be to use this prototype instead (and match all code to it) :

void fibonacci(int n, int *result).
  • I've replaced double by int, because I don't see why you'd use double to store integers.
  • I've removed x and y which you don't use in your function.

no it is not. 1st of all you are subtracting pointers to float (at --n) which might easily (even if you compile it and run it) produce access violation. It correctly complains though about types. The types that the function accepts are pointers and I bet you are passing floats.

Use this for a start:

void fibonacci(double n, double & result) {
    if(n == 1)
        result = 0;
    else if(n == 2)
        result = 1;
    else {
        // gotta figure that part out yourself
    }
}

By declaring result as a reference, your modification will change the value of the actual parameter passed. Since this is C++ references should be preferred. You can still declare n as a normal value, because you do not want to modify it. The recursive call is your homework now :)

I think it must be like this:

void fibonacci_list()
{
   int count,next=1,prev1=0,prev2;
   printf("1");
   for(count=2;count<=12;count++)
   {
       prev2=prev1;
       prev1=next;
       next=prev1+prev2;
       printf("%d ",next);
   }
   printf("...");
   return;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top