+ 3

# Can someone please explain this code?

For back round I just found out what the fibonacci sequence is. So I was like "Yo this should be dummy easy to do in java" Then I found out I'm a total blunderhead. I had no idea where to start but I knew I had to use a for loop or while loop. But I was still lost so I googled it. I found this code that is pasted at the bottom of this text. But I don't understand it at all. Mainly the for loop. public class Fibonacci { public static void main(String[] args) { int n = 10, t1 = 0, t2 = 1; System.out.print("First " + n + " terms: "); for (int i = 1; i <= n; ++i) { System.out.print(t1 + " + "); int sum = t1 + t2; t1 = t2; t2 = sum; } } } Thanks in advance

3 Answers

+ 2

Your code compute and print the first 10 values of Fibonacci sequence.
To compute the nth term of the serie, you can use the relation:
F(n) = F(0) = 0 , if n = 0
F(n) = F(1) = 1 , if n = 1
F(n) = F(n - 1) + F(n - 2), if n >= 2
The first 2 terms of the series are known as 0 and 1. So the first term to compute is the 3rd one by using the first 2 terms.
Your for loop will work 10 times as n is initialized to 10.
In your code, F(0) is represented by t1 and F(1) by t2. So you have you initial first 2 terms.
You code print in each iteration t1 as the current term of the serie, and then calculates the term following the term following the term t1 as the sum of t1 and its following term t2 and store it in the sum variable.
In order to progress in the sequence you must affect to the variable of current term (which is t1) the value of its following (stored in t2), and you do the same with the following term of t2 (stored in sum variable). In the next iteration, the next term of the serie which stored in t1 is printed.

+ 6

Basically for every iteration, you're extracting "t1" as the Fibonacci number.
The Fibonacci sequence is determined by the recurrence relation:
F(n+1)=F(n)+F(n-1)

+ 3

int n=10;
for (int i = 1; i <= n; ++i) { } //repeat 10 times
mean:
int i; // variable i initialisation (counter)
while( i <= n ) // repeat while expression is true
{
.. . // repeated code
i = i+1; // before next loop do: ++i
// again check condition expression i<=n and repeat
// or ends if expression results false
}