Select to view content in your preferred language

Return values fibonacci series java

600
1
02-24-2023 03:41 AM
hectorsalamanca
Deactivated User

I'm attempting to recursively calculate the fibonacci sequence to 100, save the resulting values in an array using the buildArray function, and then display the array contents.

here is the code:

 

public class MyFibonacci {
    public static final int MAX = 100;

    public static long[] buildArray(int MAX, int N) {
        long[] A = new long[MAX];

        A[0] = 0;
        A[1] = 1;

        for(N = 2; N < MAX; N++)
            A[N] = F(N);
        return A;
    }

    public static long F(int N) {
        if(N == 0)
            return 0;
        if(N == 1)
            return 1;
        return F(N - 1) + F(N - 2);
    }

    public static void main(String[] args) {
        for(int N = 0; N < MAX; N++)
            System.out.println(N + " " + A[N]);
    }
}

 

When I try to print A[N] in the main method, I receive a "cannot be resolved to a variable" compilation error. I'm using longs and I'm computing the series up to 100, however I'm not sure if longs are required.

The code works if I replace F(N) for A[N], but I need to put the data into an array and output that array. Is it even possible for this code to save the data in an array? I'm just getting started with Java.
Thanks.

Tags (1)
0 Kudos
1 Reply
John-Foster
Esri Contributor

@hectorsalamanca somewhere you need to call the function buildArray(), like

 long A[] = buildArray();

 

also note you don't need either parameter, the way you designed the code they aren't necessary.

 

--jf
0 Kudos