This site requires JavaScript, please enable it in your browser!
Greenfoot back
ronald
ronald wrote ...

2020/1/9

fibonacci

ronald ronald

2020/1/9

#
int num1 = 0;
int num2 = 1;
for (int i = 1; i <= 12; i++) {
    System.out.print(num2 + " ");
    int nextNum = num1 + num2;
    num1 = num2;
    num2 = nextNum;
}
I can't understand this method can you help me understand each line of code num 1 = num 2 is 0 = 0 or 1 = 1 Thank you for your help
danpost danpost

2020/1/9

#
ronald wrote...
<< Code Omitted >> I can't understand this method can you help me understand each line of code
Lines 1 and 2 set up the initial values (num1 being the last value and num2 being the current value). Line 3 and 8 block code that is to be executed 12 times. Line 4 outputs the current value. Line 5 computes the next fibonacci value. Lines 6 and 7 "shifts" the values to prepare for the next iteration of the loop.
ronald ronald

2020/1/9

#
for example int num1 = 3 and int num2 = 5 num1 + num2 = nextNum i.e. 8 num1 = num2 it is no longer 3 but 5 and num2 = nextNum is no longer 5 but 8 and so we now know num1 which is 5 which was num2 and num2 is 8 which was nextNum nextNum is now 13 num1 = num2 it is no longer 5 but 8 num2 = nextNum is no longer 8 but 13 thinking about it it comes down to the same num1 = num2 = nextNum; I don't know if we have to understand like that, is this the right reasoning ???
danpost danpost

2020/1/9

#
The reasoning is so the loop computes the values properly each time ( In(num1, num2) >> Out(num1, num2) ): Loop 1: (0, 1) >> (1, 1) Loop 2: (1, 1) >> (1, 2) Loop 3: (1, 2) >> (2, 3) Loop 4: (2, 3) >> (3, 5) Loop 5: (3, 5) >> (5, 8) Loop 6: (5, 8) >> (8, 13) etc. The values at the end of one iteration need to be the "input" for the next.
ronald ronald

2020/1/10

#
thank you
You need to login to post a reply.