Results 1 to 5 of 5
Thread: Can somebody explain me this plz
 05202010, 05:37 PM #1Senior Member
 Join Date
 May 2010
 Posts
 112
 Rep Power
 0
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 thirteenthcentury 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.
answer is :
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.
 05202010, 06:16 PM #2Senior Member
 Join Date
 Feb 2010
 Location
 Ljubljana, Slovenia
 Posts
 470
 Rep Power
 6
 05202010, 06:26 PM #3Senior Member
 Join Date
 May 2010
 Posts
 112
 Rep Power
 0
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;
 05202010, 06:33 PM #4
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:rolleyes: ~ Sno ~ :rolleyes:
'~ B.S. Computer Science ~'
 05202010, 07:47 PM #5Senior Member
 Join Date
 Feb 2010
 Location
 Ljubljana, Slovenia
 Posts
 470
 Rep Power
 6
Similar Threads

Can someone explain why the red text?
By 357mag in forum JCreatorReplies: 0Last Post: 05082010, 04:29 AM 
Help explain the FOR lines please
By hydride in forum New To JavaReplies: 2Last Post: 01202010, 12:52 AM 
Can someone explain why...
By Krooger in forum AWT / SwingReplies: 1Last Post: 11192009, 07:59 AM 
Please explain Java
By MarkWilson in forum New To JavaReplies: 7Last Post: 07022008, 08:38 AM 
need to explain this code
By reached in forum New To JavaReplies: 3Last Post: 12032007, 11:01 PM
Bookmarks