I don’t get why do I need 3 variables (first, second & fibonacci)
Why does Fibonacci become int c? Isn’t it better to just declare c = 0 from the beginning?
Why do I get the desired result on the else? Wouldn’t it be faster to just put it in the if?
This is the first exercise I don’t get at all, please help me.
Course: https://www.educative.io/collection/10370001/5138612588904448
Lesson: https://www.educative.io/collection/page/10370001/5138612588904448/5176659489587200
Hi @Emilio_Parra !!
In this code
class HelloWorld {
public static void main( String args[] ) {
String fib = "";
int n = 6;
int first = 0, second = 1, fibonacci = 0;
System.out.println("Fibonacci Series upto " + n + " Terms ");
for (int c = 0; c < n; c++) {
if (c <= 1) {
fibonacci = c;
fib += String.valueOf(fibonacci) + " ";
} else {
fibonacci = first + second;
first = second;
second = fibonacci;
fib += String.valueOf(fibonacci) + " ";
}
System.out.println(fibonacci + " ");
}
}
}
-
We need 3 variables (first, second & fibonacci) because, In the Fibonacci series, each number is the sum of the two preceding ones. The variables first
and second
are used to keep track of the previous two numbers, while fibonacci
represents the current number being calculated. The initial values of first
and second
are set to 0 and 1 respectively, as these are the starting numbers of the Fibonacci sequence.
-
We didn’t declare c = 0 from the beginning because the variable c
is used as a loop counter to iterate through the desired number of terms in the Fibonacci series. It starts from 0 and goes up to n-1
(where n
is the total number of terms). The loop is responsible for calculating each Fibonacci number and updating the values of first
, second
, and fibonacci
accordingly. By initializing c
as 0, we ensure that the loop executes the correct number of times.
-
Desired result in the else
statement and we didn’t put it in the if
statement because the if-else
statement inside the loop is used to determine whether the current iteration is for the first two terms (0 and 1) or for subsequent terms. In the first two iterations (c <= 1
), the current Fibonacci number is simply equal to the loop counter (c
itself), as there are no preceding numbers to add. These values are added to the fib
string for printing.
- From the third iteration onwards, the Fibonacci number is calculated by adding the previous two numbers (
first
and second
). Therefore, the else
part is responsible for updating the variables fibonacci
, first
, and second
with the appropriate values.
- Placing the logic of the else block directly in the if block wouldn’t be correct, as it would override the initial calculation of the Fibonacci numbers and not give the correct series.
I hope it helps. Happy Learning
2 Likes
Thank you for the quick response!
I need more practice on this topic, but you definitely helped.
2 Likes