Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Fibonacci Series in Java

I was looking for a code to write the Fibonacci Series in Java and I've found this one:

public class fibonacci {
    public static void main(String args[]) {
        int n1 = 0, n2 = 1, n3, i, display = 10;
        System.out.print(n1 + " " + n2); //printing 0 and 1

        for (i = 1; i <= display; i++) //loop starts
        {
            n3 = n1 + n2;
            System.out.print(" " + n3);
            n1 = n2;
            n2 = n3;
        }

    }
}

THE RESULT IS: 0 1 1 2 3 5 8 13 21 34 55 89 (Where every number is a summation of previous two number, except for the first two number shown in result)

MY QUESTION IS: What dose the n1 = n2; and n2 = n3; represent? Please explain.

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,863 Points

Hi Shamir,

Those two lines are re-assigning values to the variables after the loop runs and before the loop runs again.

Before the loop begins, n1 is initialized to 0 -- n2 is initialized to 1 -- and n3 is just declared, but not initialized until inside the loop at n3 = n1 + n2.

So, the first iteration of the loop, n3 becomes 1 + 0 (which equals 1). Then the re-assignments happen. n1 now becomes 1, and n2 also becomes 1.
The loop runs again, and this time n3 becomes 1 + 1 (which equals 2). Then the re-assignments... n1 is now 1 and n2 is now 2.
And so on...

I hope this helped. :)

Keep coding! :dizzy:

Hi Jason, You explained it very well. Thank you so much!