javaalgorithmfibonacci

printing fibonacci number series without using loops


Is there a hack to print the first n fibonacci numbers without calling a loop

for(int i=1; i<n; i++)
    System.out.println(computeF(n));

from the main program?

public static int computeF(int n)
{
    if(n==0)
    {
        return 0;
    }
    else if(n==1)
    {
        return 1;
    }
    else
    {
        return computeF(n-1)+computeF(n-2); 
    }

}

There might be a way to print the intermediate values in recursion which will print the fibonacci numbers.


Solution

  • You could use tail recursion.