sean
sean

Reputation: 19

Java Fibonacci for loop variable

This is a program which takes a command line variable, parses it into an int and the output is the fibonacci number equal to that cmd line argument. So if i enter 7, the output will be 13. since: 1 1 2 3 5 8 13 Can someone explain the b = a; inside the for loop? Since they're both already equal to 1, why do they need to be set equal to eachother?

    int a,b,c;
    int n = Integer.parseInt(args[0]);
    a = 1;
    b = 1;
    c = 0;
    if (n == 1 || n == 2)

        System.out.println(1);

    else 
    {
        for (int i = 3; i<=n; i++)
        {
            c = a + b;
            b = a;
            a = c;
        }
        System.out.println(c);
    }
}

Upvotes: 0

Views: 175

Answers (2)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

Fn = Fn-1 + Fn-2, i.e. for starting from a = 1 and b = 1, you have to calculate next fibonacci number and move a and b to the one position right.

public static long fibonacci(int n) {
    n = Math.abs(n);

    if (n == 0)
        return 0;
    if (n < 3)
        return 1;

    long a = 1;
    long b = 1;
    long c = 0;

    for (int i = 3; i <= n; i++) {
        c = a + b;
        b = a;
        a = c;
    }

    return c;
}

Upvotes: 0

dominicm00
dominicm00

Reputation: 1600

a and b are equal to 1 initially, so on the first iteration of the loop, this statement does nothing. But let's look at what happens on later iterations:

Initial state:
a = 1
b = 1
c = 0
Iteration 1:
c = 1 + 1 = 2
b = a = 1
a = c = 2
Iteration 2:
c = 1 + 2 = 3
b = a = 2
a = c = 3
Iteration 3:
c = 2 + 3 = 5
b = a = 3
a = c = 5

Essentially, a stores the previous number in the sequence, while b stores the second to last. Since the first 2 numbers of the sequence are 1, 1, b will stay as 1 for two iterations, but then change later on.

Upvotes: 1

Related Questions