# Can somebody explain me this plz

• 05-20-2010, 05:37 PM
ccie007
Can somebody explain me this plz
Hi,
I have resolved my task by researching on the Internet but I am having trouble how this mathematics is working.

question is

9. In mathematics, there is a famous sequence of numbers called the Fibonacci sequence after the thirteenth-century Italian mathematician Leonardo Fibonacci. The first two terms in this sequence are 0 and 1, and every subsequent term is the sum of the preceding two. Thus the first several numbers in the Fibonacci sequence are as
follows:
F0 = 0
F1 = 1
F2 = 1 (0 + 1)
F3 = 2 (1 + 1)
F4 = 3 (1 + 2)
F5 = 5 (2 + 3)
F6 = 8 (3 + 5)
Write a program to display the values in this sequence from F0 through F15.

-----------------------------------------------xx-------------------
import acm.program.*;

public class fibbonaci extends ConsoleProgram {
public static int fib(int n) {
int prev1=0, prev2=1;
for(int i=0; i<n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}

public void run() {
for (int i=0; i<=15; i++)

println("F"+i+"="+fib(i)+", ");

}

}

Can somebody explain me this bit plz:
public static int fib(int n) {
int prev1=0, prev2=1;
for(int i=0; i<n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;

thanks alot dudes.
• 05-20-2010, 06:16 PM
m00nchile
You explained the piece of code in question by yourself:
Quote:

Originally Posted by ccie007
9. In mathematics, there is a famous sequence of numbers called the Fibonacci sequence after the thirteenth-century Italian mathematician Leonardo Fibonacci. The first two terms in this sequence are 0 and 1, and every subsequent term is the sum of the preceding two.

• 05-20-2010, 06:26 PM
ccie007
Can somebody explain me this bit.

public static int fib(int n) {
int prev1=0, prev2=1;
for(int i=0; i<n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
• 05-20-2010, 06:33 PM
Sno
by lines
1.its a method, which bring in a variable integer n (ex. n could = 5)
2.for integer i is set to 0, for i is less than n, than increment i by 1 for each loop
3. integer saveprev is now the value of prev 1
4. prev1 is now the value of prev2
5. prev 2 is now the value of saveprev1 and prev2 added together
6. end for loop
7. return the value of prev1 to the place where the fib method was called

so in this for loop
becomes saveprev1 = 0
prev1 becomes 1
prev2 become 0+1
return prev1
• 05-20-2010, 07:47 PM
m00nchile
As I said, your first post contained the explanation of the method you were asking about. Just reposting the question does not make it valid again. Do some work on your own, it'll do you good in the long run.