Please explain how Java from this code gets the value of Fibonacci numbers? Everything is logical except for b = ab ??

int a = 0; int b = 1; for(int i=0; i<10; i++){ System.out.print(a+" "); a = a+b; b=ab; } 
  • 2
    Have you tried debugging? And at every turn, watch what happens. - Vartlok
  • 2
    This is such a way in b to keep the old value a . - Nofate

1 answer 1

Consider this from a mathematical point of view. Let in the n th iteration of the cycle a = x , b = y . Then, if we execute the line a = a + b , it turns out that a = x + y . In the subsequent execution of the line b = a - b we get b = (x + y) - y = x . Thus, in b we get the previous value of a , and in a - the next value calculated according to the rules of the Fibonacci sequence.