I found this really cool exercise that maybe all of us, in one time of our lives, we saw the Fibonacci sequence in mathematics and this will be a small explanation of how it works in code with a couple lines.
Well, basically the sequence consist that every number after the first two is the sum of the two preceding ones.
So the xn are the sequence and we start with 0, so 0 + 1 = 1, then 1 + 1 = 2, then 2 + 1 = 3, then 3 + 2 = 5, etc.. etc.. etc… And how this works in code, well this is the souce code:
As you can see it looks really simple and easy, but how it works?, well the key is on these 3 lines:
so if we can replace each value on each loop we can see how the sequence starts to begin, so let’s start to replace values with the first loop at the beginning we have “a” and “b” with a default value, in these case 1 and 0, so if we replace on the first loop
our result of the sequence should be “a”, now if we replace the numbers of the second loop, we should have this
the third loop
the fourth loop
fifth loop
sixth loop
etc.. etc.. etc..
output
So maybe it’s a simple thing but I really like to see how some simple things work