I’m having a little troubling understanding the code below. I’ve worked out the vales for each of the variables for each loop and I understand how the values for each variable change after each loop but I’m confused about how int a = b; represents the sum of the two previous values. I was stuck on this problem for a long time and solved the problem only through trial and error.
I really don’t understand how int a = b; represents the sum of the two previous values. I was convinced that since int c = a + b; sums both variable a and variable b that was the variable i wanted to print in my program. Can you explain how int a represents the sum of the two previous values and why int c does not.
public class Fibonacci extends ConsoleProgram{
public void run(){
int i = 0;
int a = 0;
int b = 1;
while ( i <= 12) {
println(a);
i++;
int c = a + b;
a = b;
b = c;
}
}
}
I like to think of it as a staircase:
An arbitrary step would look like:
After the one step,
cacts likebandbacts likea. But what aboutaandd? Since your solution is iterative, you just say thatabecomesdand repeat the process again in a loop:Or in code: