Hello, tell me please. There is a workable code that displays Fibonacci numbers:

public class Fibonachi2 { public static void main(String[] args) { int[] a = new int[10]; a[0] = 1; a[1] = 1; for(int i = 0; i < a.length; i++) { if(i > 2) { a[i] = a[i - 2] + a[i - 1]; System.out.print(a[i] + " "); } } } 

}

Result: 1 1 2 3 5 8 13

But I'm interested in how he displays the first two units? After all, according to the condition:

  if(i > 2) { a[i] = a[i - 2] + a[i - 1]; System.out.print(a[i] + " "); } 

it must display the elements on the screen, starting with 4 elements of the array (System.out.print (a [3] + ""); etc.).

  • one
    Why not turn on the debugger and debug the cycle in stages, looking at what's going on inside there? - Alexey Shimansky

2 answers 2

Elements are displayed on the screen, starting with the fourth.

When i=3 we get:

 a[3] = a[1] + a[2] = 1 + 0 = 1 

When i=4 :

 a[4] = a[2] + a[3] = 0 + 1 = 1 

When creating an array, it is initialized with zeros, then you explicitly initialize the first and second elements as units, the remaining elements remain zero.

    When you initialize an array int[] a = new int[10]; , it is filled with zeros:

     {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 

    Next, after the lines

     a[0] = 1; a[1] = 1; 

    Get

     {1, 1, 0, 0, 0, 0, 0, 0, 0, 0} 

    Well, then everything is simple: when the first time is triggered, the conditions if(i > 2) , i.e. when i = 3 we get:

      a[i - 2] + a[i - 1]; => a[1] + a[2] => 1 + 0 => 1 

    with i = 4

      a[i - 2] + a[i - 1]; => a[2] + a[3] => 1 + 0 => 1 

    and here you have two units

    And further on increasing ...